Returing Values

In [4]:
import math
In [1]:
def square(x):
    # Two local variables:
    # * `x`, our one positional, formal parameter
    # * `result` the result of our squaring calculation
    result = x**2
    
    return result  # return the calculated value
In [2]:
num = square(10000)  # Actual parameter
In [3]:
print(num)
100000000
In [5]:
res = math.sqrt(num)
In [6]:
print(res)
10000.0

What if you forgot to return?

In [7]:
def square2(x):
    # Two local variables:
    # * `x`, our one positional, formal parameter
    # * `result` the result of our squaring calculation
    result = x**2
    
    return
    #return result  # return the calculated value
In [12]:
num = square2(10000)  # Actual parameter
In [13]:
print(num)
None
In [14]:
res = math.sqrt(num)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-3d5927273524> in <module>()
----> 1 res = math.sqrt(num)

TypeError: must be real number, not NoneType

Distance Formula

In [24]:
from graphics import Point

def distance(p1, p2):
    # p1 = point1, p2 = point2
    sqdiff1 = square(p2.getX() - p1.getX())
    sqdiff2 = square(p2.getY() - p1.getY())
    
    dist = math.sqrt(sqdiff1 + sqdiff2)
    
    #dist = math.sqrt(square(p2.getX() - p1.getX()) + square(p2.getY() - p1.getY()))
    return dist
In [25]:
point1 = Point(23,45)
point2 = Point(54,233)

d = distance(point1, point2)
In [26]:
print(d)
190.53870997778904
In [27]:
distance("23,45", "54,233")
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-27-badea9ce622f> in <module>()
----> 1 distance("23,45", "54,233")

<ipython-input-24-564f576b77e5> in distance(p1, p2)
      2 
      3 def distance(p1, p2):
----> 4     sqdiff1 = square(p2.getX() - p1.getX())
      5     sqdiff2 = square(p2.getY() - p1.getY())
      6     dist = math.sqrt(sqdiff1 + sqdiff2)

AttributeError: 'str' object has no attribute 'getX'
In [29]:
from graphics import Point

def distance(p1, p2):
    if not (isinstance(p1, Point) or isinstance(p2, Point)):
            print("Not point objects!")
            return
            
    sqdiff1 = square(p2.getX() - p1.getX())
    sqdiff2 = square(p2.getY() - p1.getY())
    
    dist = math.sqrt(sqdiff1 + sqdiff2)
    
    #dist = math.sqrt(square(p2.getX() - p1.getX()) + square(p2.getY() - p1.getY()))
    return dist

Returning Multiple Values

In [1]:
def sum_diff(x, y):
    _sum = x + y
    diff = x - y
    return _sum, diff
In [2]:
sum_diff(34,566)
Out[2]:
(600, -532)
In [3]:
s, d = sum_diff(34,566)
print(s, d)
600 -532