循環
----------------------------------------------------------------
for i in range (1,10)
print '2 to the %d power is %d' % (i , 2**i )
range(i,j)函數建立一個整數序列,這個序列從第i數開始(包括i)到第j數為止( 不包括j)
a = range(5) # a = [0,1,2,3,4]
b = range(1,8) # b = [1,2,3,4,5,6,7]
c = range(0,14,3) # c = [0,3,6,9,12] 其中3為步長
d = range(8,1,-1) # d = [8,7,6,5,4,3,2] 其中-1為步長
for 語句可以迭代任何類型序列:
a = 'hello world'
for c in a:
print c
b = [ 'Dave' , 'Mark' , 'Ann' , 'Phil' ]
for name in b:
print name
range()函數根據起始值,終止值及涉及步進三個參數在內存中建立一個列表 ,當需要一個很大的列表時,這個既占內存又費時間
為了克服它的缺點,Python提供了xrange()函數:
for i in xrange(1,10):
print '2 to the %d power is %d' % (i , 2**i )
a = xrange(1000000000) # a = [ 0 , 1 , 2 , ... , 99999999 ]
b
----------------------------------------------------------------
for i in range (1,10)
print '2 to the %d power is %d' % (i , 2**i )
range(i,j)函數建立一個整數序列,這個序列從第i數開始(包括i)到第j數為止( 不包括j)
a = range(5) # a = [0,1,2,3,4]
b = range(1,8) # b = [1,2,3,4,5,6,7]
c = range(0,14,3) # c = [0,3,6,9,12] 其中3為步長
d = range(8,1,-1) # d = [8,7,6,5,4,3,2] 其中-1為步長
for 語句可以迭代任何類型序列:
a = 'hello world'
for c in a:
print c
b = [ 'Dave' , 'Mark' , 'Ann' , 'Phil' ]
for name in b:
print name
range()函數根據起始值,終止值及涉及步進三個參數在內存中建立一個列表 ,當需要一個很大的列表時,這個既占內存又費時間
為了克服它的缺點,Python提供了xrange()函數:
for i in xrange(1,10):
print '2 to the %d power is %d' % (i , 2**i )
a = xrange(1000000000) # a = [ 0 , 1 , 2 , ... , 99999999 ]
b