10/07/13


In [ ]:

Chapter 7 - Iteration

Multiple Assignment


In [1]:
x = 1

x = x + 1
x = x + 1
x = x + 1

print x


4

while loop


In [3]:
while x <= 100:
    x = x + 1

print x


101

Countdown and print_n revisited


In [5]:
def countdown(n):
    x = n
    while x > 0:
        print x
        x = x - 1
countdown(10)


10
9
8
7
6
5
4
3
2
1

In [8]:
def print_n(s, n):
    while n > 0:
        print s
        n = n - 1
print_n("xkcd", 5)


xkcd
xkcd
xkcd
xkcd
xkcd

break keyword


In [9]:
while True:
    line = raw_input('> ')
    if line == 'done':
        break
    print line

print 'Done!'


> ted
ted
> hi ted
hi ted
> i'm bored
i'm bored
> done
Done!

In [16]:
a = 42.0
x = 33.0
while True:
    print x
    y = float( (x + a/x) / 2 )
    if y == x:
        break
    x = y


33.0
17.1363636364
9.79364600916
7.04107040543
6.50303627014
6.48077891844
6.48074069852
6.48074069841

In [17]:
import math
print math.sqrt(42)


6.48074069841

In [ ]: