Menu

Python Conditional Statements Loops and Functions

Data science frequently involves applying rules to records, repeating calculations, and processing information from multiple sources. Writing individual instructions for every observation becomes impractical when datasets contain thousands or millions of records.

Python provides conditional statements, loops, and functions to automate these operations.

Conditional statements control program execution based on logical conditions, loops repeat instructions, and functions organise reusable operations into independent blocks of code.

Together, these programming concepts support data validation, automated calculations, file processing, and analytical workflows.

What Are Conditional Statements in Python?

Conditional statements determine which instructions execute depending on whether a condition evaluates to true or false.

Python uses three primary keywords.

Keyword Purpose
if Evaluates the initial condition
elif Evaluates another condition if earlier conditions are false
else Executes when no preceding condition is satisfied

Python identifies code blocks through indentation rather than curly braces.

Using the if Statement

Consider an online store that offers free delivery for orders above ₹2,000.

order_value = 2500if order_value > 2000:    print("Free Delivery")

Output:

Free Delivery

The statement executes because the order value satisfies the condition.

Using if and else

An else block handles the alternative outcome.

order_value = 1500if order_value > 2000:    print("Free Delivery")else:    print("Delivery Charges Apply")

Output:

Delivery Charges Apply

Only one branch executes because the condition evaluates to false.

Using if, elif, and else

Multiple conditions can be evaluated using elif.

Consider a retailer classifying customers according to total spending.

customer_spending = 12000if customer_spending >= 20000:    category = "High Value"elif customer_spending >= 5000:    category = "Regular"else:    category = "Occasional"print(category)

Output:

Regular

The first condition is false, but the second condition is true.

Python therefore assigns the customer to the regular category.

This approach is useful for customer segmentation based on predefined business rules.

What Are Loops in Python?

Loops execute a block of instructions repeatedly.

Python provides two primary loop types:

  • for loops iterate over elements in an iterable.
  • while loops continue executing while a condition remains true.

Loops are useful for processing collections, validating records, and automating repetitive calculations.

How Does a for Loop Work?

A for loop iterates through elements in a collection.

Consider a list containing daily sales figures.

daily_sales = [1200, 1500, 1800, 2000, 2500]for sale in daily_sales:    print(sale)

Output:

1200
1500
1800
2000
2500

The loop assigns each list element to the variable sale and executes the print statement.

Calculating Total Sales Using a Loop

daily_sales = [1200, 1500, 1800, 2000, 2500]total_sales = 0for sale in daily_sales:    total_sales += saleprint("Total Sales:", total_sales)

Output:

Total Sales: 9000

The variable total_sales acts as an accumulator.

Each iteration adds the current sales value to the running total.

Although Python provides the built-in sum() function for this task, understanding accumulation helps explain more complex data-processing algorithms.

Using range() in Python

The range() function generates an integer sequence that can be used for iteration.

for number in range(1, 6):    print(number)

Output:

1
2
3
4
5

The ending value is excluded.

This behaviour is important when processing array indices or repeating operations a specific number of times.

How Does a while Loop Work?

A while loop repeats instructions as long as its condition remains true.

count = 1while count <= 5:    print(count)    count += 1

Output:

1
2
3
4
5

The variable count increases during each iteration.

The loop stops when count becomes greater than 5.

Failing to update the loop condition correctly may cause an infinite loop.

When Should You Use for and while Loops?

Feature for Loop while Loop
Main Purpose Iterate through an iterable Repeat while a condition is true
Common Input Lists, strings, ranges Boolean conditions
Typical Use Processing records Repeating validation or retry logic
Termination Iterable exhausted Condition becomes false

A for loop is generally more suitable when iterating through a known collection.

A while loop is useful when the number of iterations depends on a changing condition.

What Are break and continue Statements?

Python provides loop-control statements that modify normal iteration.

break Statement

The break statement immediately terminates the nearest enclosing loop.

numbers = [10, 20, 30, 40, 50]for number in numbers:    if number == 30:        break    print(number)

Output:

10
20

The loop stops after encountering 30.

continue Statement

The continue statement skips the remaining instructions in the current iteration.

numbers = [10, 20, 30, 40, 50]for number in numbers:    if number == 30:        continue    print(number)

Output:

10
20
40
50

These statements are useful when processing datasets containing records that should be skipped or when searching for specific values.

What Are Functions in Python?

A function is a reusable block of code that performs a defined operation.

Functions reduce repetition, improve readability, and make calculations easier to test.

Python functions are created using the def keyword.

Creating a Basic Function

def greet_customer(name):    return "Hello, " + namemessage = greet_customer("Aarav")print(message)

Output:

Hello, Aarav

The function accepts a parameter named name and returns a greeting.

Parameters vs Arguments

Parameters are names defined in a function declaration.

Arguments are the actual values supplied when calling the function.

For example:

def calculate_revenue(price, quantity):    return price * quantityrevenue = calculate_revenue(1500, 4)print(revenue)

Output:

6000

Here, price and quantity are parameters, while 1500 and 4 are arguments.

How Are Functions Used in Data Science?

Functions help maintain consistent calculations across datasets.

Consider a data scientist calculating average sales for multiple regions.

def calculate_average(values):    if len(values) == 0:        return None    return sum(values) / len(values)north_sales = [2000, 2500, 3000]south_sales = [1500, 2000, 2500]print(calculate_average(north_sales))print(calculate_average(south_sales))

Output:

2500.0
2000.0

The function checks whether the input collection is empty before performing division.

This prevents a division-by-zero error.

The same function can be reused for different datasets without duplicating the calculation.

What Is the Difference Between return and print()?

The print() function displays information.

The return statement sends a value back to the calling code.

Consider:

def square(number):    return number ** 2result = square(5)print(result + 10)

Output:

35

Because square() returns a value, its result can be stored and used in subsequent calculations.

A function that only prints a result does not automatically return that value.

This distinction is particularly important in data science pipelines where outputs from one processing stage become inputs to another.

How Do Conditional Statements and Functions Support Data Cleaning?

Consider a dataset containing transaction amounts.

The objective is to identify invalid negative amounts while retaining valid transactions.

transactions = [1500, 2500, -100, 3200, -50]def validate_transaction(amount):    return amount >= 0valid_transactions = []for amount in transactions:    if validate_transaction(amount):        valid_transactions.append(amount)print(valid_transactions)

Output:

[1500, 2500, 3200]

The function checks whether each transaction amount is non-negative.

The loop processes individual observations, while the conditional statement determines whether each value should be included.

This example assumes negative values are invalid. In real financial datasets, negative amounts may legitimately represent refunds or reversals, so validation rules must reflect the data schema.

What Is the Difference Between Loops and Vectorised Operations?

Python loops are useful for understanding programming logic, but processing large numerical datasets with individual Python-level operations may be inefficient.

NumPy and Pandas provide vectorised operations that apply calculations across arrays or DataFrame columns.

For example, a Python loop can calculate revised product prices individually, while NumPy can perform the same arithmetic across an entire numerical array.

Vectorised operations frequently reduce Python-level iteration overhead and are often preferable for large numerical datasets.

However, not every operation can be vectorised efficiently, and memory requirements must also be considered.

Common Mistakes Beginners Should Avoid

  1. Incorrect indentation: Python relies on indentation to identify code blocks.
  2. Infinite while loops: A loop may continue indefinitely if its condition never becomes false.
  3. Missing return statements: Functions without an explicit return value return None.
  4. Incorrect condition order: Broad conditions placed before specific conditions may produce unintended results.
  5. Repeated calculations: Reusable functions are generally preferable to duplicating identical logic throughout a program.

Data Science Tutorial for Beginners

VA

Vaishali Ardhana



Learn via Video Course

undefined Logo

0 hrs



Get in Touch For Details