for と while ループ

Intermediate Python for Finance

Kennedy Behrman

Data Engineer, Author, Founder

コードブロックの反復

CUSIP

037833100

17275R102

68389X105

シンボル

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

for と while を練習しましょう!

Intermediate Python for Finance

Preparing Video For Download...