For- och while-loopar

Intermediate Python för finans

Kennedy Behrman

Data Engineer, Author, Founder

Upprepa ett kodblock

CUSIP

037833100

17275R102

68389X105

SYMBOL

AAPL

CSCO

ORCL

Intermediate Python för finans

Loopar

For-loop

While-loop

Intermediate Python för finans

Satsens delar

<Control Statement>
    <Code Block>
execution 1
execution 2
execution 3
Intermediate Python för finans

For-loopar

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

Exempel med lista

for x in [0, 1, 2]:
    print(x)
0
1
2
Intermediate Python för finans

Exempel med ordlista

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

Exempel med sträng

for x in "ORACLE":
    print(x)
O
R
A
C
L
E
Intermediate Python för finans

While-satser

while <expression>:
Intermediate Python för finans

Exempel med while

x = 0

while x < 5:
    print(x)
    x = (x + 1)
0
1
2
3
4
Intermediate Python för finans

Oändliga loopar

x = 0

while x <= 5:
     print(x)
Intermediate Python för finans

Hoppa över med continue

for x in [0, 1, 2, 3]:
   if x == 2:
       continue
   print(x)
0
1
3
Intermediate Python för finans

Avbryta med 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 för finans

Nu kör vi en övning!

Intermediate Python för finans

Preparing Video For Download...