Part I: Python Fundamentals

Chapter 2

Python Essentials for Engineers

schedule15 min readfitness_center5 exercises

Every engineering discipline has a working language — a set of terms, conventions, and shorthand that practitioners use to communicate precisely. Drilling engineers talk about WOB, ROP, and BHA. Reservoir engineers talk about Sw, Bo, and OOIP. These terms exist because precision matters. An ambiguous instruction on a rig floor can cost lives.

Python has its own working language: variables, data types, functions, and control flow. These are not abstract computer science concepts. They are the building blocks you use to express engineering calculations in code. This chapter teaches each of them through petroleum problems, so that by the end, you can write Python that reads like engineering and runs like software.

infoWhat You Will Learn

  • Variables, data types, and operators — how Python stores and manipulates engineering quantities
  • Control flow — how to encode engineering decision logic (safe/unsafe, economic/uneconomic)
  • Functions — how to write reusable calculations you can trust across projects
  • Error handling — how to make your code fail gracefully when real-world data is messy

Variables — Naming Your Engineering Quantities

A variable is a named container for a value. That sounds trivial, but the naming convention you adopt determines whether your code is readable six months from now or whether it looks like someone else wrote it in a language you do not speak.

In this book, we follow one rule: variable names use petroleum terminology with units appended. When you see mud_weight_ppg, you know exactly what it holds — mud weight in pounds per gallon. When you see tvd_ft, you know it is true vertical depth in feet. There is no ambiguity, no guessing.

main.py

Notice the distinction between total_depth_ft and tvd_ft. In a vertical well, measured depth and true vertical depth are the same. In a deviated or horizontal well, measured depth is always greater because the wellbore curves. This matters for pressure calculations — hydrostatic pressure depends on vertical depth, not the path the drill took to get there. Getting this wrong is a common and expensive mistake.

Data Types — What Kind of Value Are You Holding?

Python distinguishes between different kinds of values, and the distinction matters for engineering work.

main.py

Why does the type matter? Because certain operations only make sense on certain types. You can multiply porosity thickness_ft to get hydrocarbon pore volume — that is valid arithmetic on two floats. But you cannot multiply well_name reservoir_name — that is meaningless, and Python will tell you so. Type discipline prevents nonsense calculations, which in engineering, prevents nonsense decisions.

Operators — Expressing Engineering Arithmetic

Arithmetic in Python works the way you expect, with one important detail: the difference between / (true division) and // (floor division).

main.py
main.py

Comparison and Logical Operators

These are how you express engineering conditions — thresholds, limits, operating windows.

main.py

That final line — meets_porosity and meets_perm and meets_viscosity and meets_saturation — is engineering logic expressed in code. The and operator requires every condition to be true. If you used or, only one condition would need to pass, which is a different (and much less conservative) screening philosophy. The choice between and and or is not a coding decision. It is an engineering decision.

Control Flow — Encoding Engineering Decisions

If / Elif / Else — Decision Trees

Every engineering workflow has decision points. Control flow is how you encode them.

main.py

The order of the elif checks matters. If you checked water_cut_pct > 70 before oil_rate_bopd < 20, a well producing 5 bopd with 75% water cut would be classified as "High water cut" instead of "Marginal." The marginal production rate is the more urgent concern. Ordering your conditions by priority is an engineering judgment call, not a Python syntax question.

For Loops — Iterating Over Well Data

When you need to perform the same calculation on multiple wells, depths, or time periods, you use a loop.

main.py

Now let us visualize that production decline — because a chart reveals what a table of numbers cannot.

main.py
Monthly oil production rate showing typical decline behavior. The rate drops steeply in the first few months as reservoir pressure near the wellbore depletes, then flattens as the drainage area expands and the pressure gradient stabilizes.
Monthly oil production rate showing typical decline behavior. The rate drops steeply in the first few months as reservoir pressure near the wellbore depletes, then flattens as the drainage area expands and the pressure gradient stabilizes.

This is a dual-axis production plot — one of the most common visualizations in petroleum engineering. The bars show the monthly rate declining from left to right. The line shows cumulative production growing but flattening. The shape of that decline tells a reservoir engineer a great deal about what is happening underground: how fast pressure is dropping, whether the well is in transient or boundary-dominated flow, whether intervention might be needed.

We will study decline curve analysis in depth in Chapter 9. For now, the point is that a for loop, a list, and a plotting library turn raw numbers into engineering insight.

While Loops — Iterating Until a Condition Is Met

Some engineering calculations require iteration — you start with a guess, refine it, and repeat until the answer converges. This is where while loops are essential.

main.py

The friction factor converges in just a few iterations because each step gets dramatically closer to the true value. The key idea is: some engineering equations cannot be solved directly, so you guess, check, adjust, and repeat. The while loop is the structure that makes this possible.

We will use friction factors extensively in Chapter 15 (Gas Engineering) for pipeline hydraulics and pressure-drop calculations.

Functions — Building Reusable Engineering Tools

A function is a named block of code that takes inputs, performs a calculation, and returns a result. Functions are how you turn one-off calculations into reusable tools. Once you write a function that calculates hydrostatic pressure correctly, you never write that calculation again — you call the function.

main.py

There are several things to notice about how these functions are written:

Type hints (mud_weight_ppg: float) tell the reader what kind of input the function expects. They do not enforce anything at runtime, but they serve as documentation.

Docstrings (the triple-quoted text block) explain what the function does, what it takes, and what it returns. When you or a colleague uses this function six months from now, the docstring is the first thing they read. Write them.

Default parameters (overbalance_psi: float = 200) encode standard engineering practice. A 200 psi overbalance is a common default, but the function lets you override it when conditions require a different margin.

The function name is the calculation name. hydrostatic_pressure is what the function computes. Not calc_p or get_value or func1.

Building a Pressure-Depth Plot — Functions + Visualization

One of the most useful engineering visualizations is a pressure-depth plot. It shows how formation pressure, mud pressure, and fracture pressure vary with depth. The safe operating window for mud weight sits between the formation pressure (below which you get a kick) and the fracture pressure (above which you break the rock).

main.py
Pressure-depth plot showing the safe mud weight window. The shaded region between pore pressure and fracture pressure is the operating envelope. The mud weight must stay within this window at every depth — too light risks a kick, too heavy risks lost circulation.
Pressure-depth plot showing the safe mud weight window. The shaded region between pore pressure and fracture pressure is the operating envelope. The mud weight must stay within this window at every depth — too light risks a kick, too heavy risks lost circulation.

This plot is a direct product of the hydrostatic_pressure function applied across a range of depths. The red line is the formation trying to push fluid into your wellbore. The blue line is the point at which your mud breaks the rock. Your mud pressure (dashed) must stay between the two at every depth.

In reality, these gradients change with depth and geology — they are not straight lines. We will work with real pore pressure and fracture gradient data in later chapters. The principle, however, is the same: the engineer's job is to stay inside that window.

Error Handling — When Real Data Is Messy

Production data from the field is not clean. Sensors fail. Manual entries contain typos. Wells shut in unexpectedly. Your code must handle these situations without crashing, because a crashed analysis pipeline at 2 AM does not help the night-shift engineer who needs answers.

main.py
main.py

Two records failed. The code did not crash. It told you which records failed and why, then continued processing the rest. That is the difference between a script that works on clean textbook data and a tool that works on real field data.

Putting It All Together — A Well Screening Tool

Everything in this chapter — variables, types, operators, control flow, functions, error handling — combines into tools that solve real problems. Here is a complete well screening function that evaluates whether a well is a candidate for a workover.

main.py
Well screening results. Green bars indicate workover candidates — wells where the remaining potential justifies intervention. Red bars are not recommended based on current screening criteria.
Well screening results. Green bars indicate workover candidates — wells where the remaining potential justifies intervention. Red bars are not recommended based on current screening criteria.

Summary

This chapter covered the core Python constructs through petroleum engineering applications:

  • Variables store engineering quantities. Name them with petroleum terminology and units (mud_weight_ppg, tvd_ft, oil_rate_bopd) so the code reads like engineering documentation.
  • Data types (int, float, str, bool) map directly to the kinds of values engineers work with: counts, measurements, labels, and conditions.
  • Operators express engineering arithmetic and comparisons. The difference between and and or in a screening criterion is an engineering decision, not a syntax choice.
  • Control flow (if/elif/else, for, while) encodes decision logic, iterative calculations, and data processing — the same patterns that run inside production surveillance and well planning systems.
  • Functions turn one-off calculations into reusable, documented, testable tools. Write docstrings. Use type hints. Name functions after what they compute.
  • Error handling (try/except, guard clauses) makes your code robust against the messy, incomplete, sometimes contradictory data that comes from real field operations.

In the next chapter, we move from individual values to collections of data: lists, dictionaries, and the petroleum-specific file formats (CSV, JSON, LAS) that you will encounter in every engineering workflow.

Exercises

fitness_center
Exercise 2.1Practice

Formation Pressure Gradient

The formation pressure gradient is the pore pressure divided by the true vertical depth, expressed in psi/ft. Normal hydrostatic gradient for a water-...

arrow_forward
codePythonSolve Nowarrow_forward
fitness_center
Exercise 2.2Practice

Productivity Index

The productivity index (PI or J) measures how efficiently a well converts pressure drawdown into oil flow: J=qoPe−PwfJ = \frac{q_o}{P_e - P_{wf}}J=Pe​...

arrow_forward
codePythonSolve Nowarrow_forward
fitness_center
Exercise 2.3Practice

Temperature Gradient

Temperature increases with depth due to the geothermal gradient, typically 1.0–1.8°F per 100 ft in sedimentary basins. The bottomhole temperature is: ...

arrow_forward
codePythonSolve Nowarrow_forward
fitness_center
Exercise 2.4Practice

Production Alert System

Write a function production_alert(well_name, current_rate, previous_rate, water_cut) that generates alerts based on these rules: If the current rate d...

arrow_forward
codePythonSolve Nowarrow_forward
fitness_center
Exercise 2.5Practice

Unit Consistency Checker

One of the most common sources of error in petroleum engineering is mixed units — accidentally using a value in meters when the formula expects feet, ...

arrow_forward
codePythonSolve Nowarrow_forward