Code Reusability
Code Reusability
CT4029
Principles of Programming
Week 3
Code Reusability, Functions
Learning Outcomes
2
Today’s Agenda!
• Functions
• Built-In Functions
• Type conversion (int, float)
• Math functions (sin, sqrt)
• Build Your Own Function
• Arguments & Parameters
3
Functions
4
Functions
“A function is a unit of code that is often defined by its role within a greater
code structure. Specifically, a function contains a unit of code that works on
various inputs, many of which are variables, and produces concrete results
involving changes to variable values or actual operations based on the inputs.”
- Techopedia
5
Functions - Operation
• If you have operations that are performed in various different parts of the program,
then it makes sense to remove the repeated code and create a separate function or
procedure that can be called from those places instead.
• Not only will this reduce the size of your program, but it will make the code easier to
maintain, and it will remove the possibility that some of the code segments are
updated, but not others.
• Functions eliminate the code repetition
• Encourage code reusability
6
Stored (and reused) Steps
def hello(): Program:
print Output:
(“Hello”) def thing():
print (“Fun”) print (“Hello”)
print (“Fun”) Hello
hello() Fun
thing()
Print(“Zip”) Zip
print (“Zip”) thing()
Hello
Fun
hello()
8
Built-in Functions
9
Function Definition (1/2)
10
Function Definition (2/2)
Argument
Assignment 'w'
Result
>>> big = max(“Hello world”)
>>> print (big)
>>> small = min(“Hello world”)
>>> print (small)>>>
11
Max Function (1/2)
12
Max Function (2/2)
def max(inp):
blah
“Hello world” blah ‘w’
(a string) for x in y: (a string)
blah
blah
13
Type Conversions
>>> print (float(99) / 100)
0.99
• When you put an integer and floating >>> i = 42
point in an expression the integer is >>> type(i)
<type 'int'>
implicitly converted to a float >>> f = float(i)
• You can control this with the built in >>> print (f)
42.0
functions int() and float() >>> type(f)
<type 'float'>
>>> print (1 + 2 * float(3) / 4 – 5)
-2.5
14
String Conversions >>> sval = '123'
>>> type(sval)
<type 'str'>
• You can also use int() and float() >>> print (sval + 1)
Traceback (most recent call last):
to convert between strings and File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int'
integers >>> ival = int(sval)
>>> type(ival)
• You will get an error if the string <type 'int'>
>>> print (ival + 1)
does not contain numeric 124
>>> nsv = 'hello bob'
characters >>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
15
Functions - Operation
>>> num1 = 4 num1 = 4
>>> num2 = 6 num2 = 6
>>> total = num1 + num2
>>> print (total) def add():
sum = num1 + num2
print (sum)
add() add()
Output: Output:
10 10
16
Functions - Operation
>>> num1 = 4 num1 = 4
>>> num2 = 6 num2 = 6
>>> total = num1 + num2
>>> print (total) def add():
sum = num1 + num2
>>> num1 = 5 print (sum)
>>> num2 = 10 add() add()
>>> total = num1 + num2
>>> print (total) num1 = 5
num2 = 10
add()
Output: Output:
15 15
17
Build Your Own Functions
18
Building our Own Functions
def print_lyrics():
print ("I'm a lumberjack, and I'm okay.”)
print (“I sleep all night and I work all day.”)
19
Example
x=5
print (“Hello”)
20
Definitions and Uses
• Once we have defined a function, we can call (or invoke) it as many times
as we like
• This is the store and reuse pattern
21
Example
x=5
print (“Hello”)
def print_lyrics():
Output:
print ("I'm a lumberjack, and I’m okay.”) Hello
print (“I sleep all night and I work all day.”) Yo
7
print (“Yo”) I'm a lumberjack, and I'm okay.
x=x+2
I sleep all night and I work all day.
print (x)
print_lyrics()
22
Arguments and Parameters
23
Arguments
• An argument is a value we pass into the function as its input when we call
the function
• We use arguments so we can direct the function to do different kinds of
work when we call it at different times
• We put the arguments in parenthesis after the name of the function
25
Return Values
• Often a function will take its arguments, do some computation and return a
value to be used as the value of the function call in the calling expression.
The return keyword is used for this.
Output:
def greet():
return "Hello” Hello Sam
Hello Becky
print (greet(), ”Sam”)
print (greet(), ”Becky”)
26
Return Value >>> def greet(lang):
if lang == 'es’:
return 'Hola’
• A “fruitful” function is one that produces elif lang == 'fr’:
a result (or return value) return 'Bonjour’
else:
• The return statement ends the function return 'Hello’
>>> print (greet('en’),”Glenn”)
execution and “sends back” the result of
Hello Glenn
the function >>> print (greet('es’),”Sally”)
Hola Sally
>>> print (greet('fr’),”Michael”)
Bonjour Michael
27
Arguments, Parameters, and Results
28
Multiple Parameters / Arguments
29
Void (non-fruitful) Functions
30
To function or not to function...
31
Next Session!
32
33