For and while loops

Python intermedio per la finanza

Kennedy Behrman

Data Engineer, Author, Founder

Repeating a code block

CUSIP

037833100

17275R102

68389X105

SYMBOL

AAPL

CSCO

ORCL

Python intermedio per la finanza

Loops.

For loop

While loop

Python intermedio per la finanza

Statement components

<Control Statement>
    <Code Block>
execution 1
execution 2
execution 3
Python intermedio per la finanza

For loops

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

List example

for x in [0, 1, 2]:
    print(x)
0
1
2
Python intermedio per la finanza

Dictionary example

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

String example

for x in "ORACLE":
    print(x)
O
R
A
C
L
E
Python intermedio per la finanza

While control statements

while <expression>:
Python intermedio per la finanza

While example

x = 0

while x < 5:
    print(x)
    x = (x + 1)
0
1
2
3
4
Python intermedio per la finanza

Infinite loops

x = 0

while x <= 5:
     print(x)
Python intermedio per la finanza

Skipping with continue

for x in [0, 1, 2, 3]:
   if x == 2:
       continue
   print(x)
0
1
3
Python intermedio per la finanza

Stopping with 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 intermedio per la finanza

Let's practice 'for' and 'while' loops!

Python intermedio per la finanza

Preparing Video For Download...