05. flow control

最後更新: 2016-01-07

目錄

  • if
  • except
  • for
  • while
  • range() and xrange()

if

if i < 5 :
    print 'i Smaller then 5.\n',
elif i=5 :
    pass
else:
    print 'Larger then 5.\n',

支援 ==, !=, <, <=, >, >= 不過沒有 && || !  , 而要用 and or not

  • print [1,2] < [2,1]       # True
  • print [1,2,3] < [2,1]    # True, 與數量無關

支援 is , 用來比較是否同一 object

x = [1, 2]
y = [1, 2]
print x == y
print x is y

Boolean type: True and False = 1 and 0, 而非 0 就會作為 true 處理

>>> bool(2)
True

代替 if 來做 checking:

>>> age = -1
>>> assert 0 < age < 10       # Error 而停

一次過多個條件:

if foo == 'abc' and bar == 'bac' or zoo == '123':
  print "True"

在以下情況, result 是 True

# 情況1
foo = 'abc'
bar = '111'
zoo = '123'

# 情況2
foo = 'abc'
bar = 'bac'
zoo = '888'

except

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

 


for

Syntax 1

for element in mylist:
  print(element)

Syntax 1

# 0 1 ... 9   <- 由 0 開始到
for i in range(10):
  print(i)

 * for 是支援 break continue

當 list 內只有 1 個 item 時

# for ... else in Python

for val in array[:-1]:
  do_something(val)
# only if the for terminates normally
else:
  do_something_else(array[-1])

# i == items[-1]

for i in items:
  if i == items[-1]:
    print 'The last item is: '+i

 


Iterating Over Dictionaries

 

.iterms():

d = {'x': 1, 'y': 2, 'z': 3}

for list in d.iterms():
    print list

('y', 2)
('x', 1)
('z', 3)

for key, value in d.items():
    print key, ':', value

y : 2
x : 1
z : 3

.iteritems():

>>> for key,value in my_dict.iteritems():
...     print key, value

 

 


List Comprehension

 

syntax is [ expr for var in list ]

nums = [1, 2, 3, 4]
squares = [ n * n for n in nums ]   ## [1, 4, 9, 16]

 


while

 

i = 0
while i < len(a):
    print a[i]
    i = i + 3

 


range() and xrange()

 

range() and xrange() are two functions that could be used to iterate a certain number of times in for loops

In Python 3, there is no xrange

the return type of range() is list and xrange() is xrange() object

>>> t = range(10000)
>>> print (type(t))
<type 'list'>
>>> import sys
>>> print (sys.getsizeof(t))
80072

Code

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

 

Creative Commons license icon Creative Commons license icon