You are on page 1of 27

Chapter 4:

Functions

INSY 5336: Python Programming


Zhuojun Gu
Assistant Professor
Chapter 4: Functions

INSY5339
def myprint():
Stored Statements
def myprint():
print('Hello')
print(’Hello’)
print(’World')
print(‘World’)

myprint() myprint()
print(’Hi')
myprint()
Print(‘Finished’)
print(‘Hi’)

• Such reusable code segments


myprint() are called functions
• Functions can be built in or
print(’Finished') user defined
Types of Functions

Two kinds of functions in Python:

• Built-in functions provided by Python. E.g.


print(), input(), type(), float(), int(), etc.
– built-in function names are treated as reserved
words
• User defined functions
Max Function
>>> big = max('Hello world')
>>> print(big)
w

'Hello world' max() 'w'


(a string) function (a string)

• A built-in function is a black box of


code that perform a certain task
Built-in functions

• Built-in functions are always available


User Defined Functions

• Defined by us
• Defined by someone else
Functions defined by us
• We create a new function using the def
keyword followed by optional parameters
in parentheses
• We indent the body of the function
• This defines the function but does not
execute the body of the function

def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
Using a function

• Define the function in the program


• Invoke it as many times as needed

x = 5
print('Hello')

def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all
day.')

print('Yo')
x = x + 2
print(x)
Function 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 parentheses after the
name of the function

big = max('Hello world')

argument
Function Parameters
• A parameter is a >>> def greet(lang):
... if lang == 'es':
variable which we use ... print('Hola')
in the function ...
...
elif lang == 'fr':
print('Bonjour')
definition. ... else:
... print('Hello')
• It is a “handle” that ...
allows the code in the >>> greet('en')
Hello
function to access the >>> greet('es')
arguments for a Hola
>>> greet('fr')
particular function Bonjour
invocation. >>>
Return Values
• Often a function will take
>>> def greet(lang):
its arguments, do some ... if lang == 'es':
computation, and return ... return 'Hola'
a value ... elif lang == 'fr':
• The return keyword is ... return 'Bonjour'
used for this. ... else:
... return 'Hello'
• A “fruitful” function is one ...
that produces a result (or >>> print(greet('en'),'Glenn')
Hello Glenn
return value) >>> print(greet('es'),'Sally')
• The return statement Hola Sally
ends the function >>> print(greet('fr'),'Michael')
execution and “sends Bonjour Michael
>>>
back” the result of the
function
Arguments, Parameters & Results

>>> big = max('Hello world')


>>> print(big)
w Parameter

def max(inp):
blah
blah
'Hello world' 'w'
for x in inp:
blah
blah
Argument return 'w' Result
Optional Parameters
def multiply(x, y, z=1, a=1):
return(x*y*z*a)

print(multiply(2,3))
print(multiply(2,3,2))
print(multiply(2))

• A function can have a list of parameters, some


of which have a default value
• These default valued parameters are called
optional parameters
• All required parameters must be listed before
any optional parameters
To function or not to function
• Organize your code into “paragraphs” -
capture a complete thought and “name it”
• Don’t repeat yourself - make it work once
and then reuse it
• If something gets too long or complex,
break it up into logical chunks and put
those chunks in functions
• Make a library of common stuff that you
do over and over - perhaps share this
with your friends...
Some Examples
def proc(x):
return(x + 2)
def main():
x = proc(5)
print(x)
main()

• It is common to write a main() function to call


other functions
• The function definitions and calls can be in
different Jupyter Notebook cells
Example Problem
A nutritionist who works for a fitness club helps members by
evaluating their diets. As part of her evaluation, she asks members
for the number of fat grams, protein grams and carbohydrate grams
that they consumed in a day. Then, she calculates the number of
calories that result from the fat, using the following formula:
calories from fat = fat grams * 9
Next, she calculates the number of calories that result from the
protein, using the following formula:
calories from protein = protein grams * 4
Finally, she calculates the number of calories that result from the
carbohydrates, using the following formula:
calories from carbs = carb grams * 4
Define a function that will accept the fat grams and carb grams
consumed as input and display the total calories consumed.
Example Solution
A nutritionist who works for a fitness club helps members by evaluating their diets.
As part of her evaluation, she asks members for the number of fat grams, protein
grams and carbohydrate grams that they consumed in a day. Then, she calculates
the number of calories that result from the fat, using the following formula:
calories from fat = fat grams * 9
Next, she calculates the number of calories that result from the protein, using the
following formula:
calories from protein = protein grams * 4
Finally, she calculates the number of calories that result from the carbohydrates,
using the following formula:
calories from carbs = carb grams * 4
Define a function that will accept the fat grams and carb grams consumed as input
and display the total calories consumed.

def compute_consumption(fat_gm, pro_gms, carb_gms):


return (fat_gm * 9 + (carb_gm +pro_gms) * 4)

compute_consumption(20,25,80)
Functions written by others

• Functions written by others can be


used in our programs by the import
command
Modules and Functions
fibo.py file Main program
def fib(n): # write Fibonacci import fibo
series up to n fibo.fib(1000)
a, b = 0, 1 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
while b < n: fibo.fib2(100)
print(b, end=' ') [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
a, b = b, a+b
print()

def fib2(n): # return Fibonacci


series up to n • Write the module in a file
result = []
a, b = 0, 1 • The module can contain functions
while b < n: • In the main program, import the
result.append(b)
a, b = b, a+b module and use the functions
return result
Common Modules: random

• The Random module has functions to


generate pseudo random numbers
• random.random() gives a pseudo
random number
• Random.randint(5,10) return a pseudo
random integer between 5 and 9
import random
for i in range(10):
x = random.random()
print(x)
Common Modules: math

• The Math module has functions to


perform familiar mathematical functions
• math.log10(x) gives the log to base 10
of x. This is used in regressions
• math.sqrt(x) gives the square root of x

import math
print(math.sqrt(x))
Common Modules: re

• The re module has functions to perform


pattern matching
• Pattern matching is used to manipulate
textual data
• re.match() and re.search() are useful
functions import re
pattern = "Cookie"
sequence = "Cookie"
if re.match(pattern, sequence):
print("Match!")
else: print("Not a match!")
Summary
§ Functions
§ Built-in functions
§ User defined functions
§ Built-in functions are reserved words
§ def command used to define a function
§ Arguments, Parameters & Return values
§ Guidelines for user function definitions
§ Modules
§ Common Modules
To Do List for Next Class

• Read Chapters 4 and 5


• Execute code snippets and
chapter exercises in the book
• Start working on Homework 1
Acknowledgements/Contribu
tions
§ These slides are Copyright 2010- Charles R. Severance
(www.dr-chuck.com) of the University of Michigan School of
Information and made available under a Creative
Commons Attribution 4.0 License. Please maintain this last
slide in all copies of the document to comply with the
attribution requirements of the license. If you make a
change, feel free to add your name and organization to the
list of contributors on this page as you republish the
materials.

§ Initial Development: Charles Severance, University of


Michigan School of Information

§ Updated 2018: Jayarajan Samuel, University of Texas at


Arlington, College of Business
INSY5339

You might also like