2015年8月3日 星期一

Python 流程控制(二)



if 

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...

for 

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12


>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']


Range (n) 產生0~n-1序列


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

a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
     print(i, a[i])

0 Mary
1 had
2 a
3 little
5 lamb


while 

a = ['Mary', 'had', 'a', 'little', 'lamb']
i=0
while i < len(a):
    print(i, a[i])
    i+=1
0 Mary 1 had 2 a 3 little 4 lamb






沒有留言 :

張貼留言