Learn Python IF ELSE, ELIF, FOR, WHILE and functions with industrial automation examples for temperature, alarms, modes, sequences and SQL/report preparation.
Architecture: IF Else, Loops & Functions
IF Else, Loops & Functions
Process Value
Read or define plant value
Temp_Act = 860.0Condition
Compare against engineering rule
if Temp_Act > Temp_Set:Decision
Choose normal/alarm branch
Alarm = TrueLoop
Repeat across tags/records
for value in values:Function
Group reusable logic
def check_alarm(...):Return
Send result to next layer
return alarm1. IF, ELIF and ELSE
Temp_Set = 850.0
Temp_Act = 872.5 if Temp_Act > Temp_Set + 20: print("High Temperature Alarm")
elif Temp_Act > Temp_Set: print("Above Setpoint")
else: print("Temperature Normal")2. Boolean logic for interlocks
Auto_Mode = True
Door_Closed = True
Fan_Running = True if Auto_Mode and Door_Closed and Fan_Running: print("Sequence Permissive OK")
else: print("Start blocked")3. FOR loop for multiple process values
values = [850.2, 851.0, 849.8]
for value in values: print("Temperature:", value)4. WHILE loop and stop condition
count = 1
while count <= 5: print("Cycle", count) count += 1while loop needs a condition that can eventually become false.5. Functions and return values
def check_high_temp(actual, setpoint, tolerance=20.0): alarm = actual > setpoint + tolerance return alarm High_Temp_Alarm = check_high_temp(872.5, 850.0)
print(High_Temp_Alarm)6. Industrial mini-practical
def motor_permissive(auto_mode, e_stop_ok, overload_ok): return auto_mode and e_stop_ok and overload_ok motors = [ ("Fan-1", True, True, True), ("Pump-1", True, True, False),
] for name, auto, estop, overload in motors: status = motor_permissive(auto, estop, overload) print(name, "READY" if status else "BLOCKED")
Frequently Asked Questions
What is the difference between if and elif?
if starts a conditional decision; elif checks another condition only when earlier conditions were false.
When should I use for instead of while?
Use for when iterating over a known collection or range; use while when repetition depends on a condition.
Why use functions in automation scripts?
Functions group reusable logic, reduce duplication and make testing and maintenance easier.
