for 與 while 迴圈

Intermediate Python for Finance

Kennedy Behrman

Data Engineer, Author, Founder

重複執行程式區塊

CUSIP

037833100

17275R102

68389X105

SYMBOL

AAPL

CSCO

ORCL

Intermediate Python for Finance

迴圈。

For 迴圈

While 迴圈

Intermediate Python for Finance

敘述的組成

<Control Statement>
    <Code Block>
execution 1
execution 2
execution 3
Intermediate Python for Finance

For 迴圈

for <variable> in <sequence>:
for x in [0, 1, 2]:
d = {'key': 'value1'}
for x in d:
for x in "ORACLE":
Intermediate Python for Finance

列表範例

for x in [0, 1, 2]:
    print(x)
0
1
2
Intermediate Python for Finance

字典範例

symbols = {'037833100': 'AAPL',
           '17275R102': 'CSCO'
           '68389X105': 'ORCL'}
for k in symbols:
    print(symbols[k])
AAPL
CSCO
ORCL
Intermediate Python for Finance

字串範例

for x in "ORACLE":
    print(x)
O
R
A
C
L
E
Intermediate Python for Finance

While 控制敘述

while <expression>:
Intermediate Python for Finance

While 範例

x = 0

while x < 5:
    print(x)
    x = (x + 1)
0
1
2
3
4
Intermediate Python for Finance

無窮迴圈

x = 0

while x <= 5:
     print(x)
Intermediate Python for Finance

用 continue 略過

for x in [0, 1, 2, 3]:
   if x == 2:
       continue
   print(x)
0
1
3
Intermediate Python for Finance

用 break 停止。

while True:
    transaction = get_transaction()
    if transaction['symbol'] == 'ORCL':
        print('The current symbol is ORCL, break now')
        break
    print('Not ORCL')
Not ORCL
Not ORCL
Not ORCL
The current symbol is ORCL, break now
Intermediate Python for Finance

一起來練習吧!

Intermediate Python for Finance

Preparing Video For Download...