Menu

Handling Errors and Writing Reliable Code

Handling Errors and Writing Reliable Code

Data often contains unexpected values, so programs should handle common errors gracefully. Python uses exceptions to report problems that occur during execution.

Using try and except

Consider a situation where a numerical value is supplied as text.

value = "1250"

try:

amount = float(value)

print("Amount:", amount)

except ValueError:

print("The supplied value is not numeric.")

If value contains "unknown", Python raises a ValueError, and the exception handler displays a useful message instead of terminating the program unexpectedly.

Validating Data Before Calculations

A calculation such as an average requires at least one observation.

def calculate_average(values):

if len(values) == 0:

return None

return sum(values) / len(values)

print(calculate_average([10, 20, 30]))  # 20.0

print(calculate_average([]))            # None

Returning None for an empty collection makes the missing result explicit. In a real data science workflow, you should decide how to handle missing or invalid values based on the problem rather than automatically replacing them with zero.

Using Clear Variable Names and Comments

Readable code is especially important when an analysis contains multiple calculations.

# Calculate the average order value

order_values = [450, 800, 650, 1200]

average_order_value = sum(order_values) / len(order_values)

print(f"Average order value: ₹{average_order_value:.2f}")

Descriptive names, meaningful comments, and small reusable functions make analytical code easier for teammates to understand and maintain.


Python for Data Science

VA

Vishalini A



Learn via Video Course

undefined Logo

NaN hrs



Get in Touch For Details