Notes 9/23/13

Recap

Keyboard input, or how to get info from the user, using raw_input:


In [1]:
name = raw_input("What's your name? ")
print "Hello", name


What's your name? ted
Hello ted

In [5]:
age = raw_input("How old are you? ")
print float(age)


How old are you? 5
5.0

Fruitful functions


In [6]:
import math
def area(radius):
    return math.pi * radius**2

print area(5)


78.5398163397

In [7]:
def test2():
    print "hey"
    return

def echo(something):
    return something
    
def bad():
    return echo

In [9]:
def distance(x1, y1, x2, y2):
    return 0.0

distance(5,6,7,8)


Out[9]:
0.0

In [10]:
def distance(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    print 'dx is', dx
    print 'dy is', dy
    return 0.0

distance(5,6,7,8)


dx is 2
dy is 2
Out[10]:
0.0

In [11]:
def distance(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    dsquared = dx**2 + dy**2
    print 'dsquared is: ', dsquared
    return 0.0
distance(5,6,7,8)


dsquared is:  8
Out[11]:
0.0

In [13]:
import math
def distance(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    dsquared = dx**2 + dy**2
    result = math.sqrt(dsquared)
    return result
distance(1,4,17,19)


Out[13]:
21.93171219946131

Recursion


In [14]:
def factorial(n):
    space = ' ' * (4 * n)
    print space, 'factorial', n
    if n == 0:
        print space, 'returning 1'
        return 1
    else:
        recurse = factorial(n-1)
        result = n * recurse
        print space, 'returning', result
        return result
factorial(6)


                         factorial 6
                     factorial 5
                 factorial 4
             factorial 3
         factorial 2
     factorial 1
 factorial 0
 returning 1
     returning 1
         returning 2
             returning 6
                 returning 24
                     returning 120
                         returning 720
Out[14]:
720