Published 5月 29, 2018 by with 0 comment

快快樂樂學Python - 07

Python Lab

今天學循環 for x in ..., while


1. 可以用for x in..., 把list 或 tuple 的元素列出來
>>> numbers = ['1', '2', '3', '4', '5']
>>> for N in numbers:
... print (N)
...
1
2
3
4
5
>>>


2. (1+2+3+4+5)整數之和
>>> sum = 0
>>> for x in [1, 2, 3, 4, 5]:
... sum = sum + x
...
>>> print (sum)
15
>>>


3. range (), 可自動生成一個整數數列, 再用list 轉換
>>> list (range(5))
[0, 1, 2, 3, 4]
>>>
>>> sum = 0
>>> for x in range (5):
... sum = sum + x
...
>>> print (sum)
10
>>>


4. while, 只要條件滿足, 就不斷循環. 不滿足條件就退出循環.
計算1-10之間, 所有偶數和
>>> sum = 0
>>> n = 10
>>> while n > 0:
... sum = sum + n
... n = n - 2
...
>>> print (sum)
30
>>>


5. break: 提前退出循環. 印出1-10的整數, 但超過8就不要印了
>>> n = 1
>>> while n <= 10:
... if n > 8:
... break
... print (n)
... n = n + 1
...
1
2
3
4
5
6
7
8
>>>


6. contiune: 可以提前結束本次循環, 在開始下一輪循環. 印出1-10的整數, 但奇數就不要印了
>>> n = 0
>>> while n < 10:
... n = n + 1
... if n % 2 != 0:
... continue
... print (n)
...
2
4
6
8
10
>>>


Example
#20170512
#07_01.py
#list的每個名字印出 Hello, xxx!
# -*- coding: utf-8 -*-
L = ['Bart', 'Lisa', 'Peter']
for i in L:
print ('Hello,',L,'!')


最初發表 / 最後更新: 2017.05.12 / 2018.05.29

0 comments:

張貼留言