Loops and Conditionals
Flow Control¶
Flow control statements allow us to change the execution path of our code. Instead of running every line from top to bottom, we can make decisions (Conditionals) or repeat tasks (Loops).
Conditionals (if, elif, else)¶
Execute a block of code if a certain condition is true, otherwise execute another block.
Conditional statements check if a logical condition is True.
if: If the condition is true, execute the code.elif: “Else If” - Checked only if the previous if failed.else: Executed if none of the above were true.
yield_tons = 2.5
if yield_tons > 5.0:
print("High Yield")
elif yield_tons >= 3.0:
print("Average Yield")
else:
print("Low Yield")Output
Low Yield
for loop¶
Repeats a block of code a specific number of times or for each item in an iterable.
crops = ["Palay", "Corn", "Coconut", "Mango"]
print("--- Surveyed Crops ---")
for crop in crops:
print(f"Inspecting: {crop}")Output
--- Surveyed Crops ---
Inspecting: Palay
Inspecting: Corn
Inspecting: Coconut
Inspecting: Mango
Using range(): To loop a specific number of times (e.g., simulating 5 plots).
# range(1, 6) goes from 1 to 5 (stops before 6)
for plot_id in range(1, 6):
print(f"Surveying Plot #{plot_id}")Output
Surveying Plot #1
Surveying Plot #2
Surveying Plot #3
Surveying Plot #4
Surveying Plot #5
while loop¶
Repeats a block of code as long as a specified condition is true.
truck_capacity = 1000 # kg
current_load = 0
print("--- Loading Truck ---")
while current_load < truck_capacity:
current_load += 100 # Add 100 kg sack
print(f"Current Load: {current_load} kg")
print("Truck is full!")Output
--- Loading Truck ---
Current Load: 100 kg
Current Load: 200 kg
Current Load: 300 kg
Current Load: 400 kg
Current Load: 500 kg
Current Load: 600 kg
Current Load: 700 kg
Current Load: 800 kg
Current Load: 900 kg
Current Load: 1000 kg
Truck is full!
if-else + for¶
crops = ["Palay", "Corn", "Coconut", "Mango"]
for crop in crops:
if crop == "Mango":
print("Mango!")
else:
print("Not mango!")Output
Not mango!
Not mango!
Not mango!
Mango!
Loop Controls (break, continue)¶
break: Exits the loop immediately.continue: Skips the current turn and goes to the next one.
farms = [
{"name": "Farm A", "irrigated": True},
{"name": "Farm B", "irrigated": False}, # Rainfed
{"name": "Farm C", "irrigated": True}
]
print("--- Irrigation Report ---")
for farm in farms:
if not farm["irrigated"]:
print(f"Skipping {farm['name']} (Rainfed)")
continue # Skip to next farm
print(f"Surveying {farm['name']}...")Output
--- Irrigation Report ---
Surveying Farm A...
Skipping Farm B (Rainfed)
Surveying Farm C...