Lab 02: Booleans and Strings#

Topics Covered:

  • Boolean values and logical operations

  • Comparison operators for process conditions

  • String manipulation for chemical data

  • Formatting output for engineering reports

1. Demonstration#

1.1 Boolean Values and Logic#

Boolean values (True and False) are essential for decision-making in process control and safety systems. In chemical engineering, we constantly check conditions:

  • Is the temperature above the flash point?

  • Is the pressure within safe operating limits?

  • Has the reaction reached equilibrium?

Example 1.1.1: Logical Operators#

Combine boolean values using logical operators:

Operator

Meaning

Example

and

Both must be True

T_ok and P_ok

or

At least one True

alarm1 or alarm2

not

Inverts the value

not emergency

# Safety interlock system for a distillation column
temperature_ok = True   # Temperature within range
pressure_ok = True      # Pressure within range
level_ok = False        # Liquid level NOT within range (alarm!)

Example 1.1.2: Booleans and Numbers#

In Python, True equals 1 and False equals 0. This is useful for counting conditions.

# Count how many sensors are in alarm state
sensor1_alarm = True
sensor2_alarm = False
sensor3_alarm = True
sensor4_alarm = False

1.2 Strings (Text Data)#

Strings are sequences of characters used for:

  • Chemical formulas and compound names

  • Equipment labels and tag numbers

  • Process descriptions and log messages

  • Data file handling and report generation

Example 1.2.1: String Methods#

Strings have built-in methods for manipulation:

Method

Description

Example

.upper()

Convert to uppercase

"h2o".upper()"H2O"

.lower()

Convert to lowercase

"NaCl".lower()"nacl"

.strip()

Remove whitespace

" H2O ".strip()"H2O"

.replace()

Replace substring

"H2O".replace("2", "₂")

.split()

Split into list

"H-O-H".split("-")["H", "O", "H"]

# Working with chemical data
raw_formula = "  ch4  "  # Messy input data

Example 1.2.2: Searching in Strings#

Check if a substring exists or find its position.

# Process log message
log_message = "ALARM: Reactor temperature exceeded 250°C at 14:32:05"

1.3 Format a report message#

Example 1.3.1: Basic f-string Usage#

Prefix string with f and use {variable} to insert values.

# Reactor operating conditions
reactor_id = "R-101"
temperature = 185.7
pressure = 3.45
conversion = 0.923

Example 1.3.2: Number Formatting in f-strings#

Control decimal places and formatting using format specifiers:

Format

Description

Example

Output

{x:.2f}

2 decimal places

f"{3.14159:.2f}"

3.14

{x:.4f}

4 decimal places

f"{3.14159:.4f}"

3.1416

{x:.2e}

Scientific notation

f"{1234:.2e}"

1.23e+03

{x:.1%}

Percentage

f"{0.856:.1%}"

85.6%

{x:,}

Thousands separator

f"{1000000:,}"

1,000,000

# Heat exchanger calculations
heat_duty = 1256789.5  # Watts
efficiency = 0.8734
flow_rate = 0.0000523  # m³/s

1.4 Chemical Engineering Applications#

Example 1.4.1: Safety Interlock Logic#

Design a safety system that checks multiple conditions before allowing operation.

# Reactor safety interlock system
# Operating limits
T_min, T_max = 150.0, 250.0  # °C
P_min, P_max = 1.0, 10.0     # bar
level_min, level_max = 20.0, 80.0  # %

# Current readings
T_current = 185.0  # °C
P_current = 5.5    # bar
level_current = 45.0  # %

Example 1.4.2: Material Classification#

Use string operations to parse and classify chemical information.

# Chemical compound database entry
compound_data = "Ethanol;C2H5OH;78.37;46.07;Flammable"

Example 1.4.3: Product Specification Check#

Verify if a product meets quality specifications.

# Product quality specifications
product_name = "Industrial Grade Acetone"
batch_number = "ACE-2024-0156"

2. Practice Problems#

Now it’s your turn! Solve the following problems in the cells below. Make sure to:

  • Use appropriate variable names

  • Include comments explaining your logic

  • Format output clearly with units

Problem 1: Flow Regime Classification#

Based on the Reynolds number, classify the flow regime in a pipe:

Given:

  • Reynolds number (Re) = 3500

Classification criteria:

  • Re < 2300 → Laminar flow

  • 2300 ≤ Re ≤ 4000 → Transitional flow

  • Re > 4000 → Turbulent flow

Tasks:

  1. Create boolean variables: is_laminar, is_transitional, is_turbulent

  2. Print the Reynolds number and which booleans are True

  3. Create and print a status string that says “Flow regime: [regime type]”

# Your solution here
# Given
Re = 3500

Problem 2: Chemical Formula Parser#

Parse information from a chemical formula string.

Given:

formula = "Ca(OH)2"

Tasks:

  1. Find the length of the formula string

  2. Check if the formula contains:

    • Calcium (“Ca”) - store as has_calcium

    • Oxygen (“O”) - store as has_oxygen

    • Nitrogen (“N”) - store as has_nitrogen

  3. Extract the first 2 characters (the metal symbol)

  4. Check if the formula contains parentheses (indicating a polyatomic ion)

  5. Print all results with clear labels

# Your solution here
formula = "Ca(OH)2"

Problem 3: Process Log Cleaner#

Clean and standardize messy process log entries from a plant database.

Given:

log_entry = "   WARNING: pump-101 flow rate LOW at 14:25   "

Tasks:

  1. Remove leading and trailing whitespace using .strip()

  2. Convert the entire message to uppercase using .upper()

  3. Replace “PUMP-101” with “PMP-101” (standardized equipment code) using .replace()

  4. Replace “LOW” with “BELOW SETPOINT” for clarity

  5. Check if the cleaned message starts with “WARNING” using .startswith()

  6. Check if the message contains a time (look for “:” character)

  7. Split the message by spaces and count how many words it contains

  8. Print each transformation step and the final results

# Your solution here
# Given
log_entry = "   WARNING: pump-101 flow rate LOW at 14:25   "

Problem 4: Reaction Yield Analysis#

Analyze a batch reaction and determine if it meets production targets.

Given data:

  • Reaction: “Esterification of Acetic Acid”

  • Reactor ID: “R-201”

  • Theoretical yield: 500.0 kg

  • Actual yield: 423.5 kg

  • Target yield: 80%

Tasks:

  1. Calculate the percent yield: (actual/theoretical) × 100

  2. Determine if yield is acceptable (≥ 80%): store as boolean yield_acceptable

  3. Create a result string that combines the reactor ID and reaction name

  4. Print the theoretical yield, actual yield, and percent yield (use 1 decimal place)

  5. Print whether the yield is acceptable and display “ACCEPTABLE” or “BELOW TARGET”

# Your solution here
# Given data
reaction = "Esterification of Acetic Acid"
reactor_id = "R-201"
theoretical_yield = 500.0  # kg
actual_yield = 423.5       # kg

Problem 5: Equipment Tag Validator#

Validate equipment tag numbers follow the correct format.

Standard format: XXX-NNN-YY where:

  • XXX = 3-letter equipment type code (must be uppercase)

  • NNN = 3-digit unit number

  • YY = 2-character identifier

Given tags to validate:

tag1 = "PMP-101-AB"
tag2 = "pump-101-AB"
tag3 = "HX-42-C"

Tasks for each tag:

  1. Check if total length is exactly 10 characters

  2. Check if the first 3 characters are uppercase letters (use .isupper())

  3. Check if position 4 and 8 are hyphens (index 3 and 7)

  4. Store overall validity as a boolean (all conditions must be True)

  5. Print validation results for each tag

# Your solution here
# Given tags to validate
tag1 = "PMP-101-AB"
tag2 = "pump-101-AB"
tag3 = "HX-42-C"