CEN111: Programming I Lecture 3: Functions: International Burch University
CEN111: Programming I Lecture 3: Functions: International Burch University
2/1
Composition
example:
x = math.sin(degrees / 360.0 * 2 * math.pi)
is a composition
Adding new functions
A function definition specifies the name of a new function and the
sequence of statements that execute when the function is called.
example:
def print_lyrics():
print("I’m a lumberjack, and I’m okay.")
print("I sleep all night and I work all day.")
3/1
The syntax for calling the new function is the same as for built-in
functions:
>>> print_lyrics()
I’m a lumberjack, and I’m okay.
I sleep all night and I work all day.
Once we have defined a function, we can use it inside another function.
For example, to repeat the previous refrain, we could write a function
called repeat lyrics:
def repeat_lyrics():
print_lyrics()
print_lyrics()
4/1
Definitions and uses
Pulling together the code fragments from the previous section, the whole
program looks like this:
def print_lyrics():
print("I’m a lumberjack, and I’m okay.")
print("I sleep all night and I work all day.")
def repeat_lyrics():
print_lyrics()
print_lyrics()
repeat_lyrics()
Flow of execution
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order from top to bottom.
Function definitions do not alter the flow of execution of the program,
but remember that statements inside the function are not executed until
the function is called.
5/1
Parameters and arguments
Inside the function, the arguments are assigned to variables called
parameters.
def print_twice(bruce):
print(bruce)
print(bruce)
This function takes two arguments, concatenates them, and prints the
result twice. Here is an example that uses it:
6/1
>>> line1 = ’first ’
>>> line2 = ’second’
>>> cat_twice(line1, line2)
firstsecond
firstsecond
7/1