Reference: Python tutorial section 4.6
def function_name(args):
plus indented code blockreturn()
(return None
if you get to the end without a return
)def add_one(x):
x = x+1
return(x)
x = 2
print("add_one=",add_one(x),", x=",x)
## add_one= 3 , x= 2
z = 2
print("add_one=",add_one(z),", z=",z)
## add_one= 3 , z= 2
z
is immutable (a number), so it doesn’t change; if you want it to change, use z=add_one(z)
return()
The return()
statement exits the function immediately.
Changes within functions follow the standard mutability rules:
Compare:
def no_return(x):
x = [2,3,4]
return(None)
z = [1,2,3]
no_return(z)
z
## [1, 2, 3]
None
is a special word in Python.
With:
def no_return(x):
x[0] = 7
return(None)
z = [1,2,3]
no_return(z)
z
## [7, 2, 3]
def log(value,math.e)
def documented_function():
"""this is a function that does
nothing very useful
"""
return(None)
def add_function(a, b):
""" the sum of two numbers
Parameters
----------
a : num
b : num
Returns
-------
sum : num
The sum of a and b
Examples
--------
>>> add_function(2, 5)
7
>>> add_function(3, -1.4)
1.6
"""
sum = a + b
return sum
print(add_function.__doc__)
## the sum of two numbers
## Parameters
## ----------
## a : num
## b : num
## Returns
## -------
## sum : num
## The sum of a and b
## Examples
## --------
## >>> add_function(2, 5)
## 7
## >>> add_function(3, -1.4)
## 1.6
##
syntax errors vs. logic errors
Next section follows this presentation
What’s wrong with this code? (It’s meant to loop until the user enters either “y” or “n” …)
print("Please enter (y)es or (n)o")
cin = input()
while ((response != "y") or (response != "n")):
print("Please try again")
or (not response in "yn"
)
operator precedence mistakes, e.g. \(\Delta \textrm{fahrenheit} = \Delta \textrm{Celsius} \times 1.8\)
fahrdiff = celsius_high - celsius_low * 1.8
print()
statements)
if
conditionsbrowse/lurk in forums first!
nose
assert <condition>
from nose.tools import assert_equal, assert_raises
(or something)raise ErrorType("message")
, e.g. raise ValueError("non-conformable matrices")
nosetests
/run in PyCharm