๐Ÿ“ ๐Ÿ”ง๐ŸŒ Decision-Making with if-else Statements in Python#

If-Else

โš™๏ธ Theme: Monitoring an Industrial HVAC System#

In this lecture, weโ€™ll explore how if-else statements in Python can be used to manage decision-making for a Heating, Ventilation, and Air Conditioning (HVAC) system in an industrial setting.

HVAC systems need to:

  • Maintain safe temperature ranges.

  • Control humidity levels.

  • Alert operators about malfunctions.

  • Optimize energy consumption.

๐Ÿง What Are if-else Statements?#

if-else statements allow Python programs to make decisions based on conditions.

Syntax Breakdown#

if condition:
    # Code block executed if condition is True
elif another_condition:  # Optional
    # Code block executed if the `elif` condition is True
else:  # Optional
    # Code block executed if no conditions are True
  Cell In[1], line 3
    elif another_condition:  # Optional
    ^
IndentationError: expected an indented block after 'if' statement on line 1
  • if: Evaluates the first condition.

  • elif: Evaluates additional conditions if the previous ones are False.

  • else: Executes when none of the above conditions are True.

  • Indentation: Python uses indentation to define blocks of code. Consistent spacing is crucial.

๐Ÿค” Why if-else in HVAC Systems?#

HVAC systems rely on decision-making to:

  • Adjust temperature settings based on sensor data.

  • Trigger alarms for dangerous conditions.

  • Automatically switch between heating and cooling modes.

Pythonโ€™s if-else provides a simple yet powerful way to implement this logic.

๐Ÿ›  Basic Example#

Letโ€™s start with a simple example: Monitor if the room temperature is within a safe range.

# Temperature limits
min_temp = 18  # Minimum safe temperature in Celsius
max_temp = 24  # Maximum safe temperature in Celsius

# Current room temperature
current_temp = 22

# Check temperature range
if current_temp < min_temp:
    print("Warning: Temperature is too low!")
elif current_temp > max_temp:
    print("Warning: Temperature is too high!")
else:
    print("Temperature is within the safe range.")

Explanation of the Code#

  • The condition current_temp < min_temp checks if the temperature is below the safe range.

  • The elif condition current_temp > max_temp checks if the temperature exceeds the safe range.

  • The else block handles the case where the temperature is within the safe range.

Note: Only one block is executed per if-else structure.

๐Ÿ”„ if-elif-else for Multiple Conditions#

In HVAC systems, different conditions might require distinct actions. Letโ€™s expand the logic:

  • If the temperature is too low, turn on the heater.

  • If the temperature is too high, turn on the cooler.

  • Otherwise, maintain the current settings.

# Adjust HVAC settings based on temperature
if current_temp < min_temp:
    action = "Turn on the heater."
elif current_temp > max_temp:
    action = "Turn on the cooler."
else:
    action = "Maintain current settings."

print("HVAC Action:", action)

Key Points#

  • Multiple conditions are handled using elif.

  • Only the first True conditionโ€™s block is executed.

  • An else block is optional but recommended for default behavior.

๐Ÿ“‰ Using Nested if Statements#

Nested if statements allow for more complex logic. For example: Check both temperature and humidity.

# Humidity limits
min_humidity = 30  # Minimum safe humidity in %
max_humidity = 60  # Maximum safe humidity in %

# Current humidity
current_humidity = 65

# Check temperature and humidity
if current_temp < min_temp or current_temp > max_temp:
    if current_humidity < min_humidity or current_humidity > max_humidity:
        print("Alert: Both temperature and humidity are out of range!")
    else:
        print("Alert: Temperature is out of range!")
else:
    if current_humidity < min_humidity or current_humidity > max_humidity:
        print("Alert: Humidity is out of range!")
    else:
        print("Both temperature and humidity are within safe ranges.")

Nested if Structure#

  • The second if inside the first handles humidity only when temperature is out of range.

  • Use nested logic sparingly to avoid overly complex code.

๐Ÿšฆ Practical Applications#

Example: Automatically generate alerts for HVAC operators based on sensor data.

# Define function for HVAC monitoring
def hvac_monitor(temp, humidity):
    if temp < min_temp or temp > max_temp:
        if humidity < min_humidity or humidity > max_humidity:
            return "Critical Alert: Adjust temperature and humidity!"
        return "Alert: Adjust temperature!"
    elif humidity < min_humidity or humidity > max_humidity:
        return "Alert: Adjust humidity!"
    return "All systems nominal."

# Test function
print(hvac_monitor(25, 70))  # Example of high temperature and humidity
print(hvac_monitor(20, 40))  # Example of nominal conditions

๐Ÿ” Advanced Techniques: Ternary Operator#

Simplify simple if-else statements with a one-liner:

action = "Heater ON" if current_temp < min_temp else "Heater OFF"

Example: Check if energy-saving mode is required.

# Energy-saving mode
energy_saving = True if current_temp >= 20 and current_temp <= 22 else False
print("Energy-saving mode enabled:", energy_saving)

๐ŸŒ Scaling Up: Integrating with IoT#

Combine Pythonโ€™s decision-making with IoT for real-time monitoring:

  • Receive live sensor data via APIs.

  • Process data using if-else logic.

  • Send alerts or control signals to actuators.

๐ŸŽ‰ Key Takeaways#

  • if-else enables decision-making in Python, critical for engineering systems.

  • Use if-elif-else for handling multiple conditions.

  • Nested if allows for detailed checks, such as temperature and humidity monitoring.

  • Simplify logic when possible with ternary operators.

  • Integrate with IoT systems for dynamic, real-world applications.

๐Ÿš€ Build smarter HVAC systems with Python decision-making!