Menu

Conditions, Loops, and Functions

Lesson 2: Conditions, Loops, and Functions

Why are these useful?

Concept

Purpose

Analytics example

Conditions (if/elif/else)Choose what to doLabel orders as Large or Standard
Loops (for, while)Repeat a taskProcess 12 monthly files
Functions (def)Package reusable logicOne discount calculation used everywhere

Example

def revenue_after_discount(price, discount_rate):
"""Return the price after applying a discount rate (0.10 = 10%)."""
return price * (1 - discount_rate)
print(revenue_after_discount(1000, 0.10)) # 900.0

How it works

  • def defines the function. price and discount_rate are parameters.
  • return sends the result back to whoever called the function.
  • The function doesn't print anything by itself. print() displays the returned value.
  • A discount rate of 0.10 represents 10%.
  • The text in triple quotes is a docstring: a short description of what the function does.

Conditions and loops

Conditions:

order_value = 6200
if order_value >= 5000:
label = 'Large'
elif order_value >= 1000:
label = 'Medium'
else:
label = 'Small'
print(label) # Large

Operator

Meaning

==, !=Equal, not equal
>, <, >=, <=Comparisons
and, or, notCombine conditions
inMembership: region in ['South', 'East']

Loops:

files = ['jan.csv', 'feb.csv', 'mar.csv']
for f in files:
print(f"Processing {f}")

In pandas, prefer vectorised operations over loops:

Approach

Code

Speed on large data

Loopfor i in range(len(df)): ...Slow
Vectoriseddf['revenue'] = df['qty'] * df['price']Fast and clearer

Loops are still useful for general tasks, such as processing a list of files.

Common mistakes

  • Unclear function names: calc() vs calculate_net_revenue()
  • Printing instead of returning: later calculations can't use a printed value
  • Not testing edge cases: zero, negative values, missing values (None), empty lists
  • Division by zero: guard with if orders > 0:
  • Using = instead of == in conditions

Try it: Write a function that labels an order as 'Large' when its value is at least 5,000 and 'Standard' otherwise.


Data Analytics Tutorial



Learn via Video Course

Data Analysis and Processing with Python using Pandas - Data Science Course Logo

Data Analysis and Processing with Python using Pandas - Data Science Course

5 hrs



Get in Touch For Details