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
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.
for i in range(len(df)):
df.loc[i, 'total'] = (
df.loc[i, 'price']
* df.loc[i, 'qty']
)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.