Python Functions
Python Functions
Python Functions
Hide the details of your computation as long as you know what it produces
•Hide
(ABSTRACTION)
big = max('Hello
'Hello world')
world'
Assignment
'w'
Result
>>> big = max('Hello world')
>>> print(big)
w
>>> tiny = min('Hello world')
>>> print(tiny)
>>>
Max Function
A function is some
>>> big = max('Hello world') stored code that we
>>> print(big) use. A function takes
w
some input and
produces an output.
• 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.")
okay
print('I sleep all night and I work all day.')
day
print("I'm a lumberjack, and I'm okay.")
print_lyrics
print_lyrics(): print('I sleep all night and I work all day.')
x = 5
print('Hello')
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
okay Hello
print('I sleep all night and I work all day.')
day Yo
print('Yo') 7
x = x + 2
print(x)
Definitions and Uses
• Once we have defined a function, we can call (or invoke) it
as many times as we like
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
okay
print('I sleep all night and I work all day.')
day
print('Yo')
print_lyrics() Hello
x = x + 2
print(x) Yo
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
7
Arguments
• An argument is a value we pass into the function as its input
when we call the function
def greet():
return "Hello" Hello Glenn
Hello Sally
print(greet(), "Glenn")
print(greet(), "Sally")
Return Value
>>> def greet(lang):
... if lang == 'es':
• A “fruitful” function is one ... return 'Hola'
... elif lang == 'fr':
that produces a result (or ... return 'Bonjour'
return value) ... else:
... return 'Hello'
...
• The return statement ends >>> print(greet('en'),'Glenn')
the function execution and Hello Glenn
“sends back” the result of >>> print(greet('es'),'Sally')
Hola Sally
the function >>> print(greet('fr'),'Michael')
Bonjour Michael
>>>
Arguments, Parameters,
Parameters and
Results
>>> big = max('Hello world') Parameter
>>> print(big)
w
def max(inp):
blah
blah
'Hello world' for x in inp:
'w'
blah
blah
Argument return 'w'
Result
Dead code
•When
When a return statement executes, the
function terminates without executing any
subsequent statements.
•Code
Code that appears after a return statement,
or any other place the flow of execution can
never reach, is called dead code.
code
Multiple Parameters / Arguments
• We can define more than one
parameter in the function def addtwo(a, b):
definition added = a + b
return added
• We simply add more arguments
x = addtwo(3, 5)
when we call the function
print(x)
• We match the number and order 8
of arguments and parameters
Void (non-fruitful)
fruitful) Functions
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15
Any Questions?