ลูป for และ while

Python ระดับกลางสำหรับการเงิน

Kennedy Behrman

Data Engineer, Author, Founder

การทำซ้ำบล็อกโค้ด

CUSIP

037833100

17275R102

68389X105

SYMBOL

AAPL

CSCO

ORCL

Python ระดับกลางสำหรับการเงิน

ลูป

For loop

While loop

Python ระดับกลางสำหรับการเงิน

ส่วนประกอบของคำสั่ง

<Control Statement>
    <Code Block>
execution 1
execution 2
execution 3
Python ระดับกลางสำหรับการเงิน

ลูป for

for <variable> in <sequence>:
for x in [0, 1, 2]:
d = {'key': 'value1'}
for x in d:
for x in "ORACLE":
Python ระดับกลางสำหรับการเงิน

ตัวอย่างกับ list

for x in [0, 1, 2]:
    print(x)
0
1
2
Python ระดับกลางสำหรับการเงิน

ตัวอย่างกับ dictionary

symbols = {'037833100': 'AAPL',
           '17275R102': 'CSCO'
           '68389X105': 'ORCL'}
for k in symbols:
    print(symbols[k])
AAPL
CSCO
ORCL
Python ระดับกลางสำหรับการเงิน

ตัวอย่างกับ string

for x in "ORACLE":
    print(x)
O
R
A
C
L
E
Python ระดับกลางสำหรับการเงิน

คำสั่งควบคุม while

while <expression>:
Python ระดับกลางสำหรับการเงิน

ตัวอย่าง while

x = 0

while x < 5:
    print(x)
    x = (x + 1)
0
1
2
3
4
Python ระดับกลางสำหรับการเงิน

ลูปอนันต์

x = 0

while x <= 5:
     print(x)
Python ระดับกลางสำหรับการเงิน

การข้ามด้วย continue

for x in [0, 1, 2, 3]:
   if x == 2:
       continue
   print(x)
0
1
3
Python ระดับกลางสำหรับการเงิน

การหยุดด้วย 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
Python ระดับกลางสำหรับการเงิน

มาฝึกใช้ลูป 'for' และ 'while' กันเถอะ!

Python ระดับกลางสำหรับการเงิน

Preparing Video For Download...