Functions I¶
Use comments to add documentation to programs.¶
# This sentence isn't executed by Python.
adjustment = 0.5 # Neither is this - anything after '#' is ignored.
A function may take zero or more arguments.¶
We have seen some functions already — now let’s take a closer look.
An argument is a value passed into a function.
len
takes exactly one.int
,str
, andfloat
create a new value from an existing one.print
takes zero or more.print
with no arguments prints a blank line.Must always use parentheses, even if they’re empty, so that Python knows a function is being called.
print('before')
print()
print('after')
Every function returns something.¶
Every function call produces some result.
If the function doesn’t have a useful result to return, it usually returns the special value
None
.None
is a Python object that stands in anytime there is no value.
result = print('example')
print('result of print is', result)
Commonly-used built-in functions include max
, min
, and round
.¶
Use
max
to find the largest value of one or more values.Use
min
to find the smallest.Both work on character strings as well as numbers.
“Larger” and “smaller” use (0-9, A-Z, a-z) to compare letters.
print(max(1, 2, 3))
print(min('a', 'A', '0'))
Use the built-in function help to get help for a function.¶
Every built-in function has online documentation.
help(round)
The Jupyter Notebook has two ways to get help.¶
Option 1: Place the cursor near where the function is invoked in a cell (i.e., the function name or its parameters),
Hold down Shift, and press Tab.
Do this several times to expand the information returned.
Option 2: Type the function name in a cell with a question mark after it. Then run the cell.
Write your own functions in python¶
Exercise: Write the code in your notebook and replace the underscored lines to get the desired result
def max_of_two( __, __ ):
if __ > __:
return __
return __
def max_of_three( __, __, z ):
return max_of_two( x, max_of_two( __, __ ) )
print(max_of_three(3, 6, -5))
See Solution
def max_of_two( x, y ):
if x > y:
return x
return y
def max_of_three( x, y, z ):
return max_of_two( x, max_of_two( y, z ) )
print(max_of_three(3, 6, -5))
Exercise: Write the code in your notebook and replace the underscored lines to get the desired result
def sum(______):
total = 0
for number in numbers:
total += number
return total
print(sum((8, 2, 3, 0, 7)))
See Solution
def sum(numbers):
total = 0
for number in numbers:
total += number
return total
print(sum((8, 2, 3, 0, 7)))