pbPassingBI
/
Python basics for data beginner 5 min

Conditions and loops

if/elif/else and for loops — and why you will use them less than you expect.

What you'll be able to do
  • Write conditional logic
  • Write a for loop
  • Know when to use pandas instead of looping

Conditions

if revenue > 1000:
    tier = 'gold'
elif revenue > 500:
    tier = 'silver'
else:
    tier = 'bronze'

Indentation defines the block — there are no braces, and inconsistent indentation is a syntax error rather than a style issue.

Combine conditions with and, or, not (not && or ||).

Loops

for city in ['Houston', 'Dallas']:
    print(city)

for i, city in enumerate(cities):
    print(i, city)

When not to loop

Vectorise instead

Looping over DataFrame rows is the most common beginner mistake in pandas. It is often 100 times slower than the vectorised equivalent, and harder to read.

Slow and verbose
for i in range(len(df)):
    df.loc[i, 'total'] = (
        df.loc[i, 'price']
        * df.loc[i, 'qty']
    )
Fast and clear
df['total'] = df['price'] * df['qty']

pandas applies the operation to the whole column at once, in compiled code. If you are writing a loop over rows, there is almost always a column operation that does it better.

Where loops are still right

Iterating over files, over a list of report parameters, or over anything that is not a column of data. Those are fine — the guidance is specifically about looping over rows.

Key points
  • Indentation defines blocks; Python uses and / or / not
  • Looping over DataFrame rows is usually the wrong approach
  • Column operations apply to every row at once and run far faster
Check yourself