0% found this document useful (1 vote)
28 views39 pages

Understanding Python While Loops

The document discusses loops in Python. It explains while loops using an example that repeatedly divides an error by 4 until the error is less than 1. It also covers for loops, using examples to loop through a list, string, and dictionary. Finally, it discusses using loops to iterate through NumPy arrays and Pandas DataFrames. The key points are that while loops repeat as long as a condition is true, for loops iterate over each element in a sequence, and there are different approaches for looping through different data structures like dictionaries and DataFrames.

Uploaded by

Hate Vanisher
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
28 views39 pages

Understanding Python While Loops

The document discusses loops in Python. It explains while loops using an example that repeatedly divides an error by 4 until the error is less than 1. It also covers for loops, using examples to loop through a list, string, and dictionary. Finally, it discusses using loops to iterate through NumPy arrays and Pandas DataFrames. The key points are that while loops repeat as long as a condition is true, for loops iterate over each element in a sequence, and there are different approaches for looping through different data structures like dictionaries and DataFrames.

Uploaded by

Hate Vanisher
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

while loop

I N T E R M E D I AT E P Y T H O N

Hugo Bowne-Anderson
Data Scientist at DataCamp
if-elif-else
[Link]

Goes through construct only once!

z = 6
if z % 2 == 0 : # True
print("z is divisible by 2") # Executed
elif z % 3 == 0 :
print("z is divisible by 3")
else :
print("z is neither divisible by 2 nor by 3")

... # Moving on

While loop = repeated if statement

INTERMEDIATE PYTHON
While
while condition :
expression

Numerically calculating model

"repeating action until condition is met"

Example
Error starts at 50

Divide error by 4 on every run


Continue until error no longer > 1

INTERMEDIATE PYTHON
While
while condition :
expression

while_loop.py

error = 50.0

while error > 1:


error = error / 4
print(error)

Error starts at 50

Divide error by 4 on every run

Continue until error no longer > 1

INTERMEDIATE PYTHON
While
while condition :
expression

while_loop.py

error = 50.0
# 50
while error > 1: # True
error = error / 4
print(error)

12.5

INTERMEDIATE PYTHON
While
while condition :
expression

while_loop.py

error = 50.0
# 12.5
while error > 1: # True
error = error / 4
print(error)

12.5
3.125

INTERMEDIATE PYTHON
While
while condition :
expression

while_loop.py

error = 50.0
# 3.125
while error > 1: # True
error = error / 4
print(error)

12.5
3.125
0.78125

INTERMEDIATE PYTHON
While
while condition :
expression

while_loop.py

error = 50.0
# 0.78125
while error > 1: # False
error = error / 4
print(error)

12.5
3.125
0.78125

INTERMEDIATE PYTHON
While
while condition : DataCamp: session
expression
disconnected
while_loop.py Local system: Control + C

error = 50.0
while error > 1 : # always True
# error = error / 4
print(error)

50
50
50
50
50
50
50
...

INTERMEDIATE PYTHON
Let's practice!
I N T E R M E D I AT E P Y T H O N
for loop
I N T E R M E D I AT E P Y T H O N

Hugo Bowne-Anderson
Data Scientist at DataCamp
for loop
for var in seq :
expression

"for each var in seq, execute expression"

INTERMEDIATE PYTHON
fam
[Link]

fam = [1.73, 1.68, 1.71, 1.89]

print(fam)

[1.73, 1.68, 1.71, 1.89]

INTERMEDIATE PYTHON
fam
[Link]

fam = [1.73, 1.68, 1.71, 1.89]


print(fam[0])
print(fam[1])
print(fam[2])
print(fam[3])

1.73
1.68
1.71
1.89

INTERMEDIATE PYTHON
for loop
for var in seq :
expression

[Link]

fam = [1.73, 1.68, 1.71, 1.89]


for height in fam :
print(height)

INTERMEDIATE PYTHON
for loop
for var in seq :
expression

[Link]

fam = [1.73, 1.68, 1.71, 1.89]


for height in fam :
print(height)
# first iteration
# height = 1.73

1.73

INTERMEDIATE PYTHON
for loop
for var in seq :
expression

[Link]

fam = [1.73, 1.68, 1.71, 1.89]


for height in fam :
print(height)
# second iteration
# height = 1.68

1.73
1.68

INTERMEDIATE PYTHON
for loop
for var in seq :
expression

[Link]

fam = [1.73, 1.68, 1.71, 1.89]


for height in fam :
print(height)

1.73
1.68
1.71
1.89

No access to indexes

INTERMEDIATE PYTHON
for loop
for var in seq :
expression

[Link]

fam = [1.73, 1.68, 1.71, 1.89]

???

index 0: 1.73
index 1: 1.68
index 2: 1.71
index 3: 1.89

INTERMEDIATE PYTHON
enumerate
for var in seq :
expression

[Link]

fam = [1.73, 1.68, 1.71, 1.89]


for index, height in enumerate(fam) :
print("index " + str(index) + ": " + str(height))

index 0: 1.73
index 1: 1.68
index 2: 1.71
index 3: 1.89

INTERMEDIATE PYTHON
Loop over string
for var in seq :
expression

[Link]

for c in "family" :
print([Link]())

F
A
M
I
L
Y

INTERMEDIATE PYTHON
Let's practice!
I N T E R M E D I AT E P Y T H O N
Loop Data Structures
Part 1
I N T E R M E D I AT E P Y T H O N

Hugo Bowne-Anderson
Data Scientist at DataCamp
Dictionary
for var in seq :
expression

[Link]

world = { "afghanistan":30.55,
"albania":2.77,
"algeria":39.21 }

for key, value in world :


print(key + " -- " + str(value))

ValueError: too many values to


unpack (expected 2)

INTERMEDIATE PYTHON
Dictionary
for var in seq :
expression

[Link]

world = { "afghanistan":30.55,
"albania":2.77,
"algeria":39.21 }

for key, value in [Link]() :


print(key + " -- " + str(value))

algeria -- 39.21
afghanistan -- 30.55
albania -- 2.77

INTERMEDIATE PYTHON
Dictionary
for var in seq :
expression

[Link]

world = { "afghanistan":30.55,
"albania":2.77,
"algeria":39.21 }

for k, v in [Link]() :
print(k + " -- " + str(v))

algeria -- 39.21
afghanistan -- 30.55
albania -- 2.77

INTERMEDIATE PYTHON
Numpy Arrays
for var in seq :
expression

[Link]

import numpy as np
np_height = [Link]([1.73, 1.68, 1.71, 1.89, 1.79])
np_weight = [Link]([65.4, 59.2, 63.6, 88.4, 68.7])
bmi = np_weight / np_height ** 2
for val in bmi :
print(val)

21.852
20.975
21.750
24.747
21.441

INTERMEDIATE PYTHON
2D Numpy Arrays
[Link]

import numpy as np
np_height = [Link]([1.73, 1.68, 1.71, 1.89, 1.79])
np_weight = [Link]([65.4, 59.2, 63.6, 88.4, 68.7])
meas = [Link]([np_height, np_weight])

for val in meas :


print(val)

[ 1.73 1.68 1.71 1.89 1.79]


[ 65.4 59.2 63.6 88.4 68.7]

INTERMEDIATE PYTHON
2D Numpy Arrays
[Link]

import numpy as np
np_height = [Link]([1.73, 1.68, 1.71, 1.89, 1.79])
np_weight = [Link]([65.4, 59.2, 63.6, 88.4, 68.7])
meas = [Link]([np_height, np_weight])
for val in [Link](meas) :
print(val)

1.73
1.68
1.71
1.89
1.79
65.4
...

INTERMEDIATE PYTHON
Recap
Dictionary
for key, val in my_dict.items() :

Numpy array
for val in [Link](my_array) :

INTERMEDIATE PYTHON
Let's practice!
I N T E R M E D I AT E P Y T H O N
Loop Data Structures
Part 2
I N T E R M E D I AT E P Y T H O N

Hugo Bowne-Anderson
Data Scientist at DataCamp
brics
country capital area population
BR Brazil Brasilia 8.516 200.40
RU Russia Moscow 17.100 143.50
IN India New Delhi 3.286 1252.00
CH China Beijing 9.597 1357.00
SA South Africa Pretoria 1.221 52.98

[Link]

import pandas as pd
brics = pd.read_csv("[Link]", index_col = 0)

INTERMEDIATE PYTHON
for, rst try
[Link]

import pandas as pd
brics = pd.read_csv("[Link]", index_col = 0)
for val in brics :
print(val)

country
capital
area
population

INTERMEDIATE PYTHON
iterrows
[Link]

import pandas as pd
brics = pd.read_csv("[Link]", index_col = 0)

for lab, row in [Link]():


print(lab)
print(row)

BR
country Brazil
capital Brasilia
area 8.516
population 200.4
Name: BR, dtype: object
...
RU
country Russia
capital Moscow
area 17.1
population 143.5
Name: RU, dtype: object

INTERMEDIATE PYTHON
Selective print
[Link]

import pandas as pd
brics = pd.read_csv("[Link]", index_col = 0)

for lab, row in [Link]():


print(lab + ": " + row["capital"])

BR: Brasilia
RU: Moscow
IN: New Delhi
CH: Beijing
SA: Pretoria

INTERMEDIATE PYTHON
Add column
[Link]

import pandas as pd
brics = pd.read_csv("[Link]", index_col = 0)
for lab, row in [Link]() :
# - Creating Series on every iteration
[Link][lab, "name_length"] = len(row["country"])
print(brics)

country capital area population name_length


BR Brazil Brasilia 8.516 200.40 6
RU Russia Moscow 17.100 143.50 6
IN India New Delhi 3.286 1252.00 5
CH China Beijing 9.597 1357.00 5
SA South Africa Pretoria 1.221 52.98 12

INTERMEDIATE PYTHON
apply
[Link]

import pandas as pd
brics = pd.read_csv("[Link]", index_col = 0)

brics["name_length"] = brics["country"].apply(len)

print(brics)

country capital area population


BR Brazil Brasilia 8.516 200.40
RU Russia Moscow 17.100 143.50
IN India New Delhi 3.286 1252.00
CH China Beijing 9.597 1357.00
SA South Africa Pretoria 1.221 52.98

INTERMEDIATE PYTHON
Let's practice!
I N T E R M E D I AT E P Y T H O N

You might also like