Comp 150-001, MWF 12:35, Crown 105

Week 3




Monday: while loops,

def sqrt(x):
    guess = x/3
    while abs(guess * guess - x) > 0.000001:
        guess = (x/guess + guess)/2
        print(guess)  # this is just here for debugging
    return guess

How does this work with sqrt(.0000000004)? Can we fix that?

How does it work with sqrt(1e60)?

3.3: interactive while

answer='y'
while (answer != 'n')
    play()
    answer = input ('play again? y/n: ')

The use of while to process multiple lines of data. Actually, Python handles this with for loops.

For loops as while loops:

for i in range(n):
    dothing(i)

i=0
while i<n:
    dothing(i)
    i += 1

1.14

Decimals vs Floats

/ vs //

type()

format(x, .2f).  dotformat (.format()) vs format().

'the answer is {}'.format(x)

'the answer is {:.3f}'.format(x)     # or {0:.3f}

Dictionaries

d = dict()

d['one'] = 1
d['three'] = 3
d['two'] = 2

d

What does this do:

for i in d:
    print(i)

What can you do with a dictionary?

1.12.2

1.14.3:

locals()

x = 2.71828182845904523536
'
longer: {x:.5f}, shorter: {x:.3f}.'.format(**locals())