Contents
This notebook is based on "Think Python, 2Ed" by Allen B. Downey
https://greenteapress.com/wp/think-python-2e/
return
statement ends the function immediately and gives the value of the expression following it to the caller
In [1]:
def do_something_multiple( x ):
if( x < 0 ):
# Do something complicated
return -1
elif( x > 10 ):
# Do something complicated
return 1
else:
return 0
def do_something_single( x ):
# Create a value to hold the result
result = 0
if( x < 0 ):
# Do something complicated
result = -1
elif( x > 10 ):
# Do something complicated
result = 1
else:
result = 0
# Return the result
return result
radius
and result
in its circle_area
function once we are done with development, I disagreeboolean
valuesreturn
statement in a functionTrue
/False
or yes/no questionsTrue
or False
In [2]:
def is_between( x, y, z ):
return (x <= y) and (y <= z)
print( is_between( 1, 2, 3) )
print( is_between( 1, 0, 3) )
# Do this
if( is_between( 1, 2, 3 ) ):
print( 'It is between the values' )
# Don't do this
if( is_between( 1, 2, 3 ) == True ):
print( 'It is between the values' )
print
or input
functionscountdown
and fibonacci
functions, we had two choices
In [3]:
def sum_numbers_iterative( n ):
# INSERT YOUR CODE HERE
return 0
def sum_numbers_recursive( n ):
# INSERT YOUR CODE HERE
return 0
In [4]:
def multiply_iterative( n ):
# INSERT YOUR CODE HERE
return 0
def multiply_recursive( n ):
# INSERT YOUR CODE HERE
return 0
n
is a prime number using both an iterative and a recursive approach. Which was easier? Why?
In [5]:
def is_prime_iterative( n ):
# INSERT YOUR CODE HERE
return 0
def is_prime_recursive( n ):
# INSERT YOUR CODE HERE
return 0