0% found this document useful (0 votes)
11 views

Lecture 06

This document discusses functions in computer programming. It defines a function as a named sequence of statements that performs a specific task. Functions make code more modular and reusable. There are two types of functions: void functions, which execute statements but do not return a value, and value-returning functions, which return a value. Functions have local variables that are only accessible within the function. Functions also have namespaces and scopes that determine where variables can be accessed.

Uploaded by

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

Lecture 06

This document discusses functions in computer programming. It defines a function as a named sequence of statements that performs a specific task. Functions make code more modular and reusable. There are two types of functions: void functions, which execute statements but do not return a value, and value-returning functions, which return a value. Functions have local variables that are only accessible within the function. Functions also have namespaces and scopes that determine where variables can be accessed.

Uploaded by

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

Introduction to Computer Programming

-
Functions

Fall 2021

Introduction to Computer Programming - Fall 2021 1 / 57


Functions Void functions Value-Returning functions Strings as Objects

Functions

Definition
A function is a named sequence of statements that performs a specific
task or useful operation

Complex programs can be splitted into smaller tasks, each of which is


performed by a separate function
It is also named a modularized program

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

The inputs (also called arguments) are optional.


The number of inputs is not limited
The output (Returned Value) is also optional.
A function can only return 1 value (can be 1 list of values)
Introduction to Computer Programming - Fall 2021 3 / 57
Functions Void functions Value-Returning functions Strings as Objects

Functions

Function names
Just like variables, functions are named

The naming rules are the same:


can be as long as you want
cannot contain spaces
consists of alphanumeric (numbers and letters) and the underscore
first character cannot be a number (only a letter or underscore)
case sensitive (foo and Foo are 2 different functions)
cannot be a keyword (see Table 1-2 in the textbook p.57)

Because functions perform actions, programmers often use a verb in


function names.
You should choose evident names for your functions so that someone
reading your code can understand the function purpose easily
Introduction to Computer Programming - Fall 2021 4 / 57
Functions Void functions Value-Returning functions Strings as Objects

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

Example: print() function

Value-Returning functions
It executes the statements it contains and then returns a value back
to the statement that called it

Example: input() function


Introduction to Computer Programming - Fall 2021 5 / 57
Functions Void functions Value-Returning functions Strings as Objects

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

Introduction to Computer Programming - Fall 2021 7 / 57


Functions Void functions Value-Returning functions Strings as Objects

Void functions
display pattern2.py

1 #This program has 2 void functions


2

3 #we define a function named display_ladder


4 def display_ladder():
5 for i in range(3):
6 display_one_step()
7

8 #we define another function named display_one_step


9 def display_one_step():
10 print('|#####|')
11 print('| |')
12 print('| |')
13

14 #we call the display_ladder function


15 display_ladder()

Introduction to Computer Programming - Fall 2021 Link to PythonTutor 8 / 57


Functions Void functions Value-Returning functions Strings as Objects

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

Introduction to Computer Programming - Fall 2021 9 / 57


Functions Void functions Value-Returning functions Strings as Objects

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

1 #Program that will generate an error


2

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

11 #First, assign the value


12 assign_value()
13 #Second, print the value
14 print_value()

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

Introduction to Computer Programming - Fall 2021 12 / 57


Functions Void functions Value-Returning functions Strings as Objects

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

Introduction to Computer Programming - Fall 2021 13 / 57


Functions Void functions Value-Returning functions Strings as Objects

Void functions

global variable.py

1 #Example with a global variable


2

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

Introduction to Computer Programming - Fall 2021 14 / 57


Functions Void functions Value-Returning functions Strings as Objects

Void functions

global variable2.py

1 #Example with a global variable


2

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)

This example shows precedence of local variable over global variable


Link to PythonTutor
Introduction to Computer Programming - Fall 2021 15 / 57
Functions Void functions Value-Returning functions Strings as Objects

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.

If we need to write the global variable inside a function, we have to use


global keyword

Introduction to Computer Programming - Fall 2021 16 / 57


Functions Void functions Value-Returning functions Strings as Objects

Void functions

Example: writing on a global variable inside a function


1 def access_to_global():
2 global a
3 a += 1
4

6 #define a global variable


7 a = 1
8 print(a)
9

10 access_to_global()
11

12 print(a)

Introduction to Computer Programming - Fall 2021 17 / 57


Functions Void functions Value-Returning functions Strings as Objects

Void functions
Passing data into a function
Sometimes, it is useful to send one or more pieces of data into a function.

Pieces of data that are sent are called arguments


Arguments are stored in local variables called parameters

Defining a function with parameters

# this function expects 2 inputs when called:


# parameter 1 and parameter 2
def name of function(parameter 1, parameter 2):
# do stuff with parameter 1 and parameter 2

Calling a function providing arguments

name of function(5,'Hello')
Introduction to Computer Programming - Fall 2021 18 / 57
Functions Void functions Value-Returning functions Strings as Objects

Void functions

display pattern with parameter.py

1 #definition of display_ladder with one parameter


2 def display_ladder(number_of_steps):
3 for i in range(number_of_steps):
4 display_one_step()
5

6 #we define another function named display_one_step


7 def display_one_step():
8 print('|#####|')
9 print('| |')
10 print('| |')
11

12 #call display_ladder providing an argument of 5


13 display_ladder(5)

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

1 #this function has two parameters: greeting and num


2 def greet_more_input(greeting, num):
3 s = greeting * num
4 print(s)
5

6 #call the function


7 greet_more_input('hello',5)

Link to PythonTutor

Introduction to Computer Programming - Fall 2021 20 / 57


Functions Void functions Value-Returning functions Strings as Objects

Void functions

Parameters and Arguments


the arguments that you pass into a function can be referenced
within that function’s body using the parameter’s name
this is based on the position of the parameter and the order that
the arguments are passed in to the function call

Introduction to Computer Programming - Fall 2021 21 / 57


Functions Void functions Value-Returning functions Strings as Objects

Void functions

two parameters2.py

1 #this function has two parameters: greeting and num


2 def greet_more_input(greeting, num):
3 s = greeting * num
4 print(s)
5

6 #call the function


7 greet_more_input('hello',5)
8 greet_more_input(3,'hola')

Link to PythonTutor

In this example, it still works but the function was not intended this way
(according to parameters names)!!!

You need to pay attention to the correspondence between arguments and


parameters (order is important)
Introduction to Computer Programming - Fall 2021 22 / 57
Functions Void functions Value-Returning functions Strings as Objects

Void functions

main() function
It is common for a program to have a main() function that is called
when the program starts

The main() function usually contains a program’s mainline logic,


which is the overall logic of a program

Introduction to Computer Programming - Fall 2021 23 / 57


Functions Void functions Value-Returning functions Strings as Objects

Void functions
Flowchart

main() display ladder(height param) display one step()

Print
|#####|
Ask for ladder height
→ height range(height param)

Print
| |

display ladder(height) display one step()


Print
| |

Return Return Return


Introduction to Computer Programming - Fall 2021 24 / 57
Functions Void functions Value-Returning functions Strings as Objects

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

6 #definition of display_ladder with one parameter


7 def display_ladder(number_of_steps):
8 for i in range(number_of_steps):
9 display_one_step()
10

11 #fdefinition of display_one_step
12 def display_one_step():
13 print('|#####|')
14 print('| |')
15 print('| |')
16

17 #Call the main function


18 main()
Introduction to Computer Programming - Fall 2021 25 / 57
Functions Void functions Value-Returning functions Strings as Objects

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

Introduction to Computer Programming - Fall 2021 26 / 57


Functions Void functions Value-Returning functions Strings as Objects

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

1 def compute_area_rectangle(length, width):


2 area = length * width
3 print(area)

Introduction to Computer Programming - Fall 2021 27 / 57


Functions Void functions Value-Returning functions Strings as Objects

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

Introduction to Computer Programming - Fall 2021 28 / 57


Functions Void functions Value-Returning functions Strings as Objects

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

6 def compute_area_rectangle(length, width):


7 area = length * width
8 print(area)
9

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)

However, it may be useful to return a value out of the function


→ Value-Returning functions

Known examples

math.randint(1,6) str(54)
int("156") range(10)
input('foo') len("qwertyuiop")
type("Hello") print("abc") ???

Introduction to Computer Programming - Fall 2021 30 / 57


Functions Void functions Value-Returning functions Strings as Objects

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

Void functions always return a None value


Introduction to Computer Programming - Fall 2021 31 / 57
Functions Void functions Value-Returning functions Strings as Objects

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

6 #call the function


7 output = greet_more_input('hello',5)
8 print(output)
Introduction to Computer Programming - Fall 2021 32 / 57
Functions Void functions Value-Returning functions Strings as Objects

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

Introduction to Computer Programming - Fall 2021 33 / 57


Functions Void functions Value-Returning functions Strings as Objects

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)) + "!"

Introduction to Computer Programming - Fall 2021 34 / 57


Functions Void functions Value-Returning functions Strings as Objects

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)) + "!"

These 3 functions return a string:


foo() returns foo
bar() returns bar
baz() returns 10.0!
Introduction to Computer Programming - Fall 2021 35 / 57
Functions Void functions Value-Returning functions Strings as Objects

Value-Returning functions

Exercise: Area of a circle


Write a function that returns the area of a circle (πR 2 ) when given a
radius R.

Introduction to Computer Programming - Fall 2021 36 / 57


Functions Void functions Value-Returning functions Strings as Objects

Value-Returning functions

Exercise: Area of a circle


Write a function that returns the area of a circle (πR 2 ) when given a
radius R.
1 #math module for the definition of pi
2 import math
3

4 def area(R):
5 a = math.pi * (R ** 2)
6 return a

Introduction to Computer Programming - Fall 2021 37 / 57


Functions Void functions Value-Returning functions Strings as Objects

Value-Returning functions

Exercise: Area of a circle


Write a function that returns the area of a circle (πR 2 ) when given a
radius R.
1 #math module for the definition of pi
2 import math
3

4 def area(R):
5 return math.pi * (R ** 2)

Introduction to Computer Programming - Fall 2021 38 / 57


Functions Void functions Value-Returning functions Strings as Objects

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

1 def greet(greeting, num):


2 s = greeting * num
3 print(s)
4 return s

Introduction to Computer Programming - Fall 2021 39 / 57


Functions Void functions Value-Returning functions Strings as Objects

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()

Introduction to Computer Programming - Fall 2021 40 / 57


Functions Void functions Value-Returning functions Strings as Objects

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

Introduction to Computer Programming - Fall 2021 41 / 57


Functions Void functions Value-Returning functions Strings as Objects

Value-Returning functions

Multiple Return Statements


You can have multiple return statements in your function!

See the following example that calculates absolute value using


multiple return statements

1 def absolute_value(x):
2 if x >= 0:
3 return x
4 else:
5 return -x

Introduction to Computer Programming - Fall 2021 42 / 57


Functions Void functions Value-Returning functions Strings as Objects

Value-Returning functions

Multiple Return Values


You can return more than one value by:
using return with a comma separated list of values
in conjunction with multiple assignment

What do you think this prints out?

Introduction to Computer Programming - Fall 2021 43 / 57


Functions Void functions Value-Returning functions Strings as Objects

Value-Returning functions

Multiple Return Values


You can return more than one value by:
using return with a comma separated list of values
in conjunction with multiple assignment

What do you think this prints out?

1 def two_things():
2 return "two", "things"
3

4 a, b = two_things()
5 print(b, a)

Introduction to Computer Programming - Fall 2021 44 / 57


Functions Void functions Value-Returning functions Strings as Objects

Strings as Objects

Objects and Methods


object - a thing that a variable name can refer to, like a window, a
string or an integer
a method is essentially a function associated with an object; it can
be thought of as an action behavior that an object can perform
for us that means data AND functions. . . all packed into one thing

Introduction to Computer Programming - Fall 2021 45 / 57


Functions Void functions Value-Returning functions 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()

# tell leo to go get his Oscar


leo.get an oscar()

# use the object name


# followed by dot .
# and the method (it is like a regular function)

Introduction to Computer Programming - Fall 2021 46 / 57


Functions Void functions Value-Returning functions Strings as Objects

Strings as Objects

Strings as Objects
Yes. Strings are objects. So they have functions at their disposal that
they can call on themselves.

Here is a short list:


upper() and lower()
isdigit() and isalpha()
find(sub[, start[, end]])
strip()

You can find other methods or help on a given method with:


dir("any string")
help("a string".upper)

Introduction to Computer Programming - Fall 2021 47 / 57


Functions Void functions Value-Returning functions Strings as Objects

Strings as Objects

upper() and lower() methods


upper() and lower() return the string that the method was called
on in either all uppercase or all lowercase

>>> question = "lowercase Or UPPERCASE?"


>>> question.lower()
'lowercase or uppercase?'
>>> question.upper()
'LOWERCASE OR UPPERCASE?'

Introduction to Computer Programming - Fall 2021 48 / 57


Functions Void functions Value-Returning functions Strings as Objects

Strings as Objects

isdigit() and isalpha() methods


isdigit() and isalpha() test whether a string is only numbers or
letters (both return False if empty string)

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())

Introduction to Computer Programming - Fall 2021 49 / 57


Functions Void functions Value-Returning functions Strings as Objects

Strings as Objects

isdigit() and isalpha() methods


isdigit() and isalpha() test whether a string is only numbers or
letters (both return False if empty string)

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

Introduction to Computer Programming - Fall 2021 50 / 57


Functions Void functions Value-Returning functions Strings as Objects

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. . .

1 sentence = 'hello world!'


2

3 print(sentence.find("h"))
4 print(sentence.find("x"))
5 print(sentence.find("lo"))
6 print(sentence.find("World"))

Introduction to Computer Programming - Fall 2021 51 / 57


Functions Void functions Value-Returning functions Strings as Objects

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"))

Introduction to Computer Programming - Fall 2021 52 / 57


Functions Void functions Value-Returning functions Strings as Objects

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).

>>> " spaces all around ".strip()


'spaces all around'
>>> " even more spaces ".strip()
'even more spaces'
>>> "#strip hash###".strip('#')
'strip hash'

Introduction to Computer Programming - Fall 2021 53 / 57


Functions Void functions Value-Returning functions Strings as Objects

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

Introduction to Computer Programming - Fall 2021 54 / 57


Functions Void functions Value-Returning functions Strings as Objects

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

Introduction to Computer Programming - Fall 2021 56 / 57


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

1 def is_digit(s):
2 return s.isdigit()
3

4 print(is_digit("43"))
5 print(is_digit("4ab5"))

Introduction to Computer Programming - Fall 2021 57 / 57

You might also like