>>> while True:
...    print 'Type Ctrl-C to stop me!'



>>> x = 'spam'
>>> while x:                    # While x is not empty.
...     print x,
...     x = x[1:]               # Strip first character off x.
...
spam pam am m



>>> a=0; b=10
>>> while a < b:       # One way to code counter loops
...     print a,
...     a += 1         # Or, a = a+1
...
0 1 2 3 4 5 6 7 8 9



while True:
    
    
    if exitTest(): break



while 1: pass   # Type Ctrl-C to stop me!



def func1():
    pass             # add real code here later

def func2():
    pass



x = 10
while x:
    x = x-1                   # Or, x -= 1
    if x % 2 != 0: continue   # Odd?--skip print
    print x,



x = 10
while x:
    x = x-1
    if x % 2 == 0:            # Even?-- print
        print x,



>>> while 1:
...     name = raw_input('Enter name:')
...     if name == 'stop': break
...     age  = raw_input('Enter age: ')
...     print 'Hello', name, '=>', int(age) ** 2
...
Enter name:mel
Enter age: 40
Hello mel => 1600
Enter name:bob
Enter age: 30
Hello bob => 900
Enter name:stop



x = y / 2                          # For some y > 1
while x > 1:
    if y % x == 0:                 # Remainder
        print y, 'has factor', x
        break                      # Skip else
    x = x-1
else:                              # Normal exit
    print y, 'is prime'



found = False
while x and not found:
    if match(x[0]):              # Value at front?
        print 'Ni'
        found = True
    else:
        x = x[1:]                # Slice off front and repeat.
if not found:
    print 'not found'



while x:                         # Exit when x empty.
    if match(x[0]):
        print 'Ni'
        break                    # Exit, go around else.
    x = x[1:]
else:
    print 'Not found'            # Only here if exhausted x.



while ((x = next()) != NULL) {...process x...}

while True:
    x = next()
    if not x: break
    ...process x...

x = 1
while x:
    x = next()
    if x:
        ...process x...

x = next()
while x:
    ...process x...
    x = next()



>>> for x in ["spam", "eggs", "ham"]:
...     print x,
...
spam eggs ham



>>> sum = 0
>>> for x in [1, 2, 3, 4]:
...     sum = sum + x
...
>>> sum
10
>>> prod = 1
>>> for item in [1, 2, 3, 4]: prod *= item
...
>>> prod
24



>>> S = "lumberjack"
>>> T = ("and", "I'm", "okay")

>>> for x in S: print x,            # iterate over a string
...
l u m b e r j a c k

>>> for x in T: print x,            # iterate over a tuple
...
and I'm okay



>>> T = [(1, 2), (3, 4), (5, 6)]
>>> for (a, b) in T:                   # Tuple assignment at work
...     print a, b
...
1 2
3 4
5 6



>>> items = ["aaa", 111, (4, 5), 2.01]          # A set of objects
>>> tests = [(4, 5), 3.14]                      # Keys to search for
>>>
>>> for key in tests:                           # For all keys
...     for item in items:                      # For all items
...         if item == key:                     # Check for match.
...             print key, "was found"
...             break
...     else:
...         print key, "not found!"
...
(4, 5) was found
3.14 not found!



>>> for key in tests:                    # For all keys
...     if key in items:                 # Let Python check for a match.
...         print key, "was found"
...     else:
...         print key, "not found!"
...
(4, 5) was found
3.14 not found!



>>> seq1 = "spam"
>>> seq2 = "scam"
>>>
>>> res = []                     # Start empty.
>>> for x in seq1:               # Scan first sequence.
...     if x in seq2:            # Common item?
...         res.append(x)        # Add to result end.
...
>>> res
['s', 'a', 'm']



file = open('test.txt', 'r')
print file.read()

file = open('test.txt')
while True:
    char = file.read(1)          # Read by character.
    if not char: break
    print char,

for char in open('test.txt').read():
    print char

file = open('test.txt')
while True:
    line = file.readline()       # Read line by line.
    if not line: break
    print line,

file = open('test.txt', 'rb')
while True:
    chunk = file.read(10)        # Read byte chucks.
    if not chunk: break
    print chunk,

for line in open('test.txt').readlines(): 
    print line

for line in open('test.txt').xreadlines():
    print line

for line in open('test.txt'):
    print line



>>> for x in [1, 2, 3, 4]: print x ** 2,
1 4 9 16

>>> for x in (1, 2, 3, 4): print x ** 3,
1 8 27 64

>>> for x in 'spam': print x * 2,
ss pp aa mm



>>> f = open('script1.py')
>>> f.readline()
'import sys\n'
>>> f.readline()
'print sys.path\n'
>>> f.readline()
'x = 2\n'
>>> f.readline()
'print 2 ** 33\n'
>>> f.readline()
''



>>> f = open('script1.py')
>>> f.next()
'import sys\n'
>>> f.next()
'print sys.path\n'
>>> f.next()
'x = 2\n'
>>> f.next()
'print 2 ** 33\n'
>>> f.next()
Traceback (most recent call last):
  File "<pyshell#330>", line 1, in <module>
    f.next()
StopIteration



>>> for line in open('script1.py'):            # use file iterators
        print line.upper(),
	
IMPORT SYS
PRINT SYS.PATH
X = 2
PRINT 2 ** 33



>>> for line in open('script1.py').readlines():
        print line.upper(),
	
IMPORT SYS
PRINT SYS.PATH
X = 2
PRINT 2 ** 33



>>> f = open('script1.py')
>>> while True:
        line = f.readline()
        if not line: break
        print line.upper(),

same oputput    



>>> L = [1, 2, 3]
>>> I = iter(L)           # obtain an iterator object
>>> I.next()              # call next to advance to next item
1
>>> I.next()
2
>>> I.next()
3
>>> I.next()
Traceback (most recent call last):
  File "<pyshell#343>", line 1, in <module>
    I.next()
StopIteration



>>> D = {'a':1, 'b':2, 'c':3}
>>> for key in D.keys():
        print key, D[key]

a 1
c 3
b 2



>>> for key in D:
        print key, D[key]
	
a 1
c 3
b 2



>>> for line in open('script1.py'):            # use file iterators
        print line.upper(),
	
IMPORT SYS
PRINT SYS.PATH
X = 2
PRINT 2 ** 33



>>> uppers = [line.upper() for line in open('script1.py')]
>>> uppers
['IMPORT SYS\n', 'PRINT SYS.PATH\n', 'X = 2\n', 'PRINT 2 ** 33\n']

>>> map(str.upper, open('script1.py'))
['IMPORT SYS\n', 'PRINT SYS.PATH\n', 'X = 2\n', 'PRINT 2 ** 33\n']

>>> 'y = 2\n' in open('script1.py')
False
>>> 'x = 2\n' in open('script1.py')
True

>>> sorted(open('script1.py'))
['import sys\n', 'print 2 ** 33\n', 'print sys.path\n', 'x = 2\n']



>>> sorted([3, 2, 4, 1, 5, 0])           # more iteration contexts
[0, 1, 2, 3, 4, 5]
>>> sum([3, 2, 4, 1, 5, 0])
15
>>> any(['spam', '', 'ni'])
True
>>> all(['spam', '', 'ni'])
False



>>> list(open('script1.py'))
['import sys\n', 'print sys.path\n', 'x = 2\n', 'print 2 ** 33\n']

>>> tuple(open('script1.py'))
('import sys\n', 'print sys.path\n', 'x = 2\n', 'print 2 ** 33\n')

>>> '&&'.join(open('script1.py'))
'import sys\n&&print sys.path\n&&x = 2\n&&print 2 ** 33\n'

>>> a, b, c, d = open('script1.py')
>>> a, d
('import sys\n', 'print 2 ** 33\n')



>>> range(5), range(2, 5), range(0, 10, 2)
([0, 1, 2, 3, 4], [2, 3, 4], [0, 2, 4, 6, 8])



>>> range(-5, 5)
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]

>>> range(5, -5, -1)
[5, 4, 3, 2, 1, 0, -1, -2, -3, -4]



>>> for i in range(3):
...     print i, 'Pythons'
...
0 Pythons
1 Pythons
2 Pythons



>>> X = 'spam'
>>> for item in X: print item,            # Simple iteration
...
s p a m



>>> i = 0
>>> while i < len(X):                     # while loop iteration
...     print X[i],; i += 1
...
s p a m



>>> X
'spam'
>>> len(X)                                # Length of string
4
>>> range(len(X))                         # All legal offsets into X
[0, 1, 2, 3]
>>>
>>> for i in range(len(X)): print X[i],   # Manual for indexing
...
s p a m



>>> for item in X: print item,            # Simple iteration



>>> S = 'abcdefghijk'
>>> range(0, len(S), 2)
[0, 2, 4, 6, 8, 10]

>>> for i in range(0, len(S), 2): print S[i],
...
a c e g i k



for x in S[::2]: print x



>>> L = [1, 2, 3, 4, 5]

>>> for x in L:
...     x += 1
	
>>> L
[1, 2, 3, 4, 5]
>>> x
6



>>> L = [1, 2, 3, 4, 5]

>>> for i in range(len(L)):          # Add one to each item in L
...     L[i] += 1                    # Or L[i] = L[i] + 1
...
>>> L
[2, 3, 4, 5, 6]



>>> i = 0
>>> while i < len(L):
...     L[i] += 1
...     i += 1
...
>>> L
[3, 4, 5, 6, 7]



>>> L1 = [1,2,3,4]
>>> L2 = [5,6,7,8]
>>> zip(L1,L2)
[(1, 5), (2, 6), (3, 7), (4, 8)]



>>> for (x, y) in zip(L1, L2):
...     print x, y, '--', x+y
...
1 5 -- 6
2 6 -- 8
3 7 -- 10
4 8 -- 12



>>> T1, T2, T3 = (1,2,3), (4,5,6), (7,8,9)
>>> T3
(7, 8, 9)
>>> zip(T1,T2,T3)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

>>> S1 = 'abc'
>>> S2 = 'xyz123'
>>>
>>> zip(S1, S2)
[('a', 'x'), ('b', 'y'), ('c', 'z')]

>>> map(None, S1, S2)
[('a', 'x'), ('b', 'y'), ('c', 'z'), (None, '1'), (None, '2'), (None,'3')]



>>> D1 = {'spam':1, 'eggs':3, 'toast':5}
>>> D1
{'toast': 5, 'eggs': 3, 'spam': 1}

>>> D1 = {}
>>> D1['spam']  = 1
>>> D1['eggs']  = 3
>>> D1['toast'] = 5



>>> keys = ['spam', 'eggs', 'toast']
>>> vals = [1, 3, 5]



>>> zip(keys, vals)
[('spam', 1), ('eggs', 3), ('toast', 5)]

>>> D2 = {}
>>> for (k, v) in zip(keys, vals): D2[k] = v
...
>>> D2
{'toast': 5, 'eggs': 3, 'spam': 1}



>>> keys = ['spam', 'eggs', 'toast']
>>> vals = [1, 3, 5]

>>> D3 = dict(zip(keys, vals))
>>> D3
{'toast': 5, 'eggs': 3, 'spam': 1}



>>> S = 'spam'
>>> offset = 0
>>> for item in S:
        print item, 'appears at offset', offset
        offset += 1
	
s appears at offset 0
p appears at offset 1
a appears at offset 2
m appears at offset 3



>>> S = 'spam'
>>> for (offset, item) in enumerate(S):
        print item, 'appears at offset', offset

s appears at offset 0
p appears at offset 1
a appears at offset 2
m appears at offset 3



>>> E = enumerate(S)
>>> E.next()
(0, 's')
>>> E.next()
(1, 'p')



\
>>> [c * i for (i, c) in enumerate(S)]
['', 'p', 'aa', 'mmm']




>>> L = [1, 2, 3, 4, 5]
>>> for i in range(len(L)):
        L[i] += 10

>>> L
[11, 12, 13, 14, 15]



>>> L = [x + 10 for x in L]
>>> L
[21, 22, 23, 24, 25]



>>> res = []
>>> for x in L:
        res.append(x + 10)

>>> res
[21, 22, 23, 24, 25]



>>> f = open('script1.py')
>>> lines = f.readlines()
>>> lines
['import sys\n', 'print sys.path\n', 'x = 2\n', 'print 2 ** 33\n']



>>> lines = [line.rstrip() for line in lines]
>>> lines
['import sys', 'print sys.path', 'x = 2', 'print 2 ** 33']



>>> lines = [line.rstrip() for line in open('script1.py')]
>>> lines
['import sys', 'print sys.path', 'x = 2', 'print 2 ** 33']



>>> lines = [line.rstrip() for line in open('script1.py') if line[0] == 'p']
>>> lines
['print sys.path', 'print 2 ** 33']



>>> res = []
>>> for line in open('script1.py'):
        if line[0] == 'p':
            res.append(line.rstrip())
		
>>> res
['print sys.path', 'print 2 ** 33']



>>> [x + y for x in 'abc' for y in 'lmn']
['al', 'am', 'an', 'bl', 'bm', 'bn', 'cl', 'cm', 'cn']



>>> res = []
>>> for x in 'abc':
        for y in 'lmn':
            res.append(x + y)
		
>>> res
['al', 'am', 'an', 'bl', 'bm', 'bn', 'cl', 'cm', 'cn']

